【问题标题】:incompatibility for accepts_nested_attributes_for between rails 2.3.5 and rails 2.3.8在rails 2.3.5和rails 2.3.8之间的accepts_nested_attributes_for不兼容
【发布时间】:2011-03-23 17:05:42
【问题描述】:

我刚刚发现 rails 2.3.5 和 rails 2.3.8 之间的行为发生了变化,我在谷歌上找不到任何东西。

我要建模

class Book < ActiveRecord::Base
  has_many :authors
  accepts_nested_attributes_for authors
end

class Author < ActiveRecord::Base
  belongs_to :book
end

我有一个视图,用作者嵌套视图填充一本书。

进入图书控制器我有一个更新操作

def update
  @book = Book.find(params[:id])
  @book.attributes = params[:book]
  ....
end

params[:book] 看起来像这样:

{:name=>"a great book", "authors_attributes"=>{"1"=>{:id"=>"2", "_destroy"=>"", :name => "Boney M"}}}

稍后在我的过程中,我想访问我更新的集合(在保存书籍对象之前,例如用于验证),使用 rails 2.3.5 @book.authors 给了我作者集合更新了参数值 [ :book] 哈希。但是在 2.3.8 中,它给了我从数据库重新加载的作者集合。

我的问题来自函数assign_nested_attributes_for_collection_association (/usr/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/nested_attributes.rb)。它返回一个 @loaded = false 的 AssociationProxy 对象。因此,当我第一次想使用@book.authors 访问我的收藏时,它会从 db 重新加载它。 Rails 2.3.5 并非如此。

我是否在这里遗漏了什么,或者这种新行为已在某处被报告?

提前感谢您的帮助。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    不确定这是否相关,但我刚刚注意到,当我将应用程序从 2.3.5 更新到 2.3.8 时,我无法再更新相关记录。系统会忽略已存在记录的更新信息,只会添加新记录。我发现如果我想更新关联的记录,我必须从数据库中删除它,然后再次创建它。太烂了。

    class Product < ActiveRecord::Base
        has_many :allowed_design_types, :dependent => :destroy, :include => [:design_type], :order => 'design_types.name'
        has_many :design_types, :through => :allowed_design_types
        accepts_nested_attributes_for(
          :allowed_design_types, 
          :allow_destroy => true, 
          :reject_if => proc { |obj| p obj; !['1', 'true'].include?(obj.delete('allow')) }
        )
    end
    

    这在参数中被发送,但被完全忽略:

    "product"=>{"allowed_design_types_attributes"=>{"0"=>{"design_type_id"=>"5", "allow"=>"1", "product_id"=>"1", "id"=>"45", "your_price"=>"3", "_destroy"=>""}}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-03-12
      • 1970-01-01
      • 2012-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多