使用一个表单更新多个记录

时间:2013-06-17 19:36:22

标签: ruby ruby-on-rails-3 activerecord

我遇到以下情况:user有多个assets,每个asset都有一个asset_detail记录。

型号:

class User < ActiveRecord::Base
  has_many :assets
end

class Asset < ActiveRecord::Base
  has_one :asset_detail
  belongs_to :user

  accepts_nested_attributes_for :asset_detail,
  :allow_destroy => false

  attr_accessible # ...
end

class AssetDetail < ActiveRecord::Base
  belongs_to :asset

  attr_accessible # ...
end

控制器操作:

def edit
  @user   = current_user
  @assets = Asset.all
end

def update
  @user = current_user
  @user.update_attributes(params["user"])
end

查看:

= form_for @user, url: 'update action url' do |f|
  = f.fields_for :assets do |ff|
    = ff.text_field :title 
    = ff.fields_for :asset_detail do |fff|
      = fff.text_field :value

问题是所有表单字段都已正确填充,但我无法保存它们。发送表单时没有任何错误,但数据未更新。

1 个答案:

答案 0 :(得分:0)

我认为你的模型应该是这样的:

class User < ActiveRecord::Base
  attr_accessible :assets_attributes #...
  has_many :assets
  accepts_nested_attributes_for :assets_attributes
end

class Asset < ActiveRecord::Base
  attr_accessible :asset_detail_attrbutes # ...
  has_one :asset_detail
  belongs_to :user

  accepts_nested_attributes_for :asset_detail_attributes,
  :allow_destroy => false
end

原因是,您需要能够通过传递给每个模型的属性哈希来设置属性。 HTH!