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

时间:2012-09-21 16:30:21

标签: ruby-on-rails paperclip nested-attributes update-attributes

我的模型描述了段落和图像,其中每个段落都有很多图像。对于图像处理,我使用回形针。对于质量赋值,我将图像用作段落的nested_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是临时属性(不在数据库中)。如果我更新控制器或rails控制台中的段落(假设id = 1的图像确实属于第一段),则以下更新paragraph.text,但不会更新image.caption:

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

但是在不使用回形针的类似设置(嵌套临时属性)中,它按预期工作,例如对于页面,页面包含多个段落:

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

这会按预期更新页面和嵌套段落的值及其临时文本属性,这让我猜测,它可能是一个回形针问题......

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

1 个答案:

答案 0 :(得分:0)

给出images_attributes

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

我认为缺少photo密钥导致Paragraphreject_if调用的accepts_nested_attributes_for选项而被attributes['photo']拒绝。未提供时nil nil.blank? true {{1}}为{{1}},因此被拒绝。

相关问题