2013-07-10 64 views
4

我卡住了,我不知道为什么它不正常工作。 我有一个模型产品,有很多标签。 当我正确更新产品栏更新产品属性,但创建另一个标签记录,而不是只更新它。更新时导轨4嵌套属性多条记录

这里是我的代码:

查看形式:

<%= form_for ([@product.user, @product]), id: 'edit_form' do |f| %> 
     <%= render 'shared/error_messages', object: f.object %> 

     <div class="field"> 
     <%= f.label :name %><br> 
     <%= f.text_field :name %> 
     </div> 
     <div class="field"> 
     <%= f.label :description %><br> 
     <%= f.text_area :description %> 
     </div> 

     <div class="field"> 
     <%= f.fields_for :tags do |t| %> 
      <%= t.label :name %> 
      <%= t.text_field :name %> 
     <% end %> 
     </div> 


     <div class="actions"> 
     <%= f.submit %> 
     </div> 
    <% end %> 

产品型号:

class Product < ActiveRecord::Base 

     belongs_to :user, :foreign_key => "user_id" 
     has_many :tags, :dependent => :destroy 
     accepts_nested_attributes_for :tags, reject_if: :all_blank, allow_destroy: true, :update_only => true 
    end 

标签型号:

class Tag < ActiveRecord::Base 
     belongs_to :product, :foreign_key => "product_id" 
     # before_save { name.downcase! } 

    end 

产品控制器:

def edit 
     user = User.find(params[:user_id]) 
     @product = user.products.find(params[:id]) 
     @tags = @product.tags.all 

     respond_to do |format| 
      format.html 
      format.js 
     end 
     end 

     def update 
      user = User.find(params[:user_id]) 
      @product = user.products.find(params[:id]) 
      @tags = @product.tags.all 

     respond_to do |format| 
      if @product.update(product_params) 
      format.html { redirect_to([@product.user, @product], :notice => 'Product successfully updated.') } 
      else 
      format.html { render :action => "edit" } 
      end 
     end 
     end 

    def product_params 
      params.require(:product).permit(:name, :description, tags_attributes: :name) 
     end 

非常感谢

+0

你忘了标签ID字段。 –

+0

在窗体视图中? –

+0

是的。如果您没有创建id字段,它将显示标签的表单,但不会将其识别为现有标签。 –

回答

20

你要通过中证PARAMS标签ID在你的控制器

def product_params 
    params.require(:product).permit(:name, :description, tags_attributes: [:id,:name]) 
end 
+0

工作正常:D谢谢 –

+0

很高兴你有它的工作...记得要标记你的问题为回答。摇摆! – phron