0

我有以下情况: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

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

4

1 回答 1

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

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

于 2013-06-17T19:49:19.490 回答