更新嵌套的params不工作..什么错了?

时间:2010-07-06 09:40:30

标签: ruby-on-rails model nested-forms

我试图从表单中更新一些嵌套的params。我可以看到从表单中获取的参数是正确的,但数据库不会更新。

视图

<% form_for @order do |f| %>
  <% f.fields_for :itemgroups do |ff, i| %>
    <% ff.fields_for :items do |fff| %>
      <%= ff.text_field :text, :id => "textField", :disabled => true %>
      <%= ff.text_field :price, :class => "priceField", :disabled => true %>
      <%= fff.check_box :registered, :class => i %>
    <% end %>
  <% end %>
  <%= submit_tag 'Save', :disabled_with => "Saving..." %>
<% end %>

项目组类

class Itemgroup < ActiveRecord::Base
  belongs_to :order
  has_many :items, :dependent => :destroy
  has_one :kind

  accepts_nested_attributes_for :items, :kind
end

订单类

class Order < ActiveRecord::Base
  has_many :itemgroups, :dependent => :destroy
  has_many :items, :through => :itemgroups, :dependent => :destroy
  has_many :kinds, :through => :itemgroups

  accepts_nested_attributes_for :itemgroups, :allow_destroy => true

  validates_associated :itemgroups, :items ,:kinds
end

控制器的重要部分。

def update
  @order = Order.find(params[:id])

  if @order.update_attributes(params[:order])
    flash[:notice] = 'Order was successfully edited.'
    redirect_to(@order)
  else
    flash[:notice] = 'An error occured.'
    render(:action => :edit)
  end
end

2 个答案:

答案 0 :(得分:1)

更改

<% f.fields_for :itemgroups do |ff, i| %>
  <% ff.fields_for :items do |fff| %>
    <%= ff.text_field :text, :id => "textField", :disabled => true %>
    <%= ff.text_field :price, :class => "priceField", :disabled => true %>
    <%= fff.check_box :registered, :class => i %>
  <% end %>

To EDITED

<% f.fields_for :itemgroups do |ff, i| %>
    <%= ff.text_field :text, :id => "textField", :disabled => true %>
    <%= ff.text_field :price, :class => "priceField", :disabled => true %>
  <% ff.fields_for :items do |fff| %>
    <%= fff.check_box :registered, :class => i %>
  <% end %>

并检查

答案 1 :(得分:-1)

解决了问题!

class Order < ActiveRecord::Base
  has_many :itemgroups, :dependent => :destroy
  has_many :items, :through => :itemgroups, :dependent => :destroy
  has_many :kinds, :through => :itemgroups

  accepts_nested_attributes_for :itemgroups, :allow_destroy => true

  # validates_associated :itemgroups, :items ,:kinds
end

删除了validates_associated行。然后它工作