【发布时间】:2011-06-08 02:31:37
【问题描述】:
具有以下型号:
class Location < ActiveRecord::Base
has_many :group_locations
has_many :groups, :through => :group_locations
accepts_nested_attributes_for :group_locations
end
class GroupLocation < ActiveRecord::Base
belongs_to :group
belongs_to :location
end
class Group < ActiveRecord::Base
has_many :group_locations
has_many :locations, :through => :group_locations
end
rails 控制台中的以下命令不会更新相关记录:
>> l = Location.find(1)
=> #<Location id: 1, phone: "(949) 788-9999", ... created_at: "2011-06-02 00:58:07",
updated_at: "2011-06-07 23:57:32">
\>\> l.group_locations
=> [#<GroupLocation group_id: 4, location_id: 1, created_at: "2011-06-02 00:58:07",
updated_at: "2011-06-02 00:58:07">, #<GroupLocation group_id: **37**, location_id: 1,
created_at: "2011-06-02 00:58:07", updated_at: "2011-06-02 00:58:07">]
>> l.update_attributes(:phone => "(949) 788-9998", :group_locations_attributes =>
[{:group_id => 4, :location_id => 1}, {:group_id => **38**, :location_id => 1}])
=> true
>> l
=> #<Location id: 1, phone: "(949) 788-9998", ... created_at: "2011-06-02 00:58:07",
updated_at: "2011-06-08 02:05:00">
>> l.group_locations
=> [#<GroupLocation group_id: 4, location_id: 1, created_at: "2011-06-02 00:58:07",
updated_at: "2011-06-02 00:58:07">, #<GroupLocation group_id: **37**, location_id: 1,
created_at: "2011-06-02 00:58:07", updated_at: "2011-06-02 00:58:07">]
请注意,update_attributes 调用尝试将第二个 GroupLocation 更改为 group_id = 38,但没有进行更改(即使电话号码确实更改了)。查看在控制器和视图中实现时生成的代码后,将数组更改为哈希(在这种情况下创建的)没有不同的结果(和表单/控制器)具有不更新的相同效果即使主记录已更新,关联的记录也是如此。
知道要更新嵌套属性需要做什么吗?
【问题讨论】:
-
刚刚发现了一个问题——需要使属性可访问——attr_accessible group_locations_attributes。现在,问题在于它添加了更多组而不是替换现有组。例如在 update_attributes group_locations => [4, 37, 4, 38] 而不是 [4,38] 之后。
标签: has-many nested-attributes