update_attributes()不适用于嵌套属性和回形针?

问题描述:

我的模型描述段落和图像,其中每个段落has_many图像。对于图像处理,我使用回形针。对于批量分配,我使用图像作为段落的nested_attributes。相关代码:update_attributes()不适用于嵌套属性和回形针?

模型/ paragraph.rb

class Paragraph < ActiveRecord::Base 
    has_many :images, :dependent => :destroy 
    attr_accessible :text, :images_attributes, :images 
    attr_accessor :text 
    accepts_nested_attributes_for :images, :allow_destroy => true, :reject_if => proc { |attributes| attributes['photo'].blank? } 
end 

模型/ image.rb

class Image < ActiveRecord::Base 
    belongs_to :paragraph 
    has_attached_file :photo, :styles => { :original => '250*250>' } 
    attr_accessible :caption, :photo 
    attr_accessor :caption 
end 

paragraph.text和image.caption是暂时的属性(不在数据库中)。如果我更新控制器或导轨控制台中的段落(假设id = 1的图像确实属于第一段),以下更新段落text如预期,但根本不更新image.caption:

Paragraph.first.update_attributes({"text" => "foo", "images_attributes"=>{"0"=>{"caption"=>"bar", "id"=>"1"}}}) 

但是在没有使用回形针的类似设置(嵌套临时属性)中,它可以按预期工作,例如对于页面,其中一个页面的has_many段落:

Page.first.update_attributes({"paragraphs_attributes"=>{"0"=>{"text"=>"test", "id"=>"1"}}}) 

此更新页面的价值观和嵌套段落预期他们的临时文本属性,这让我猜测,这可能是一个回形针问题...

任何帮助表示赞赏!谢谢!!!

+0

我个人会将'Paragraph'数据对象的更新移动到'Paragraph',因为我不是'accep_nested_attributes_for'的最大粉丝。所以'Page.first.paragraph.update(标题:'bar',id:1)'。 – CharlesJHardy

鉴于

{"0"=>{"caption"=>"bar", "id"=>"1"}} 

images_attributes我认为缺少一个photo关键是使其通过Paragraph被拒绝,由于accepts_nested_attributes_for通话reject_if选项。 attributes['photo']将在nil未提供,nil.blank?true,因此它被拒绝。