accepts_nested_attributes_for和reject_if的回形针问题

时间:2011-01-22 05:13:28

标签: ruby-on-rails

我正在开发rails 3应用程序。

class Post < ActiveRecord::Base
  has_many :attachments
  has_many :photos
  accepts_nested_attributes_for :attachments, :allow_destroy => true, :reject_if => proc { |attrs| attrs['document'].blank? }
  accepts_nested_attributes_for :photos, :allow_destroy => true, :reject_if => proc { |attrs| attrs['image'].blank? }
end

class Attachment < ActiveRecord::Base
  belongs_to :post      
  has_attached_file :document
end

class Photo < ActiveRecord::Base
  belongs_to :post      
  has_attached_file :image, :styles => {
                                         :thumb  => "100x100#",
                                         :small  => "150x150>",
                                         :mid    => "640x640>",
                                         :large  => "800x800>"
                                       }

end

问题是“_destroy”=&gt;“1”不适用于附件和照片。 我想出如果我删除reject_if选项,它就可以了。 怎么了?

感谢。

萨姆

1 个答案:

答案 0 :(得分:1)

似乎自Rails 3.0.3以来,需要加载要销毁的关联(附件,照片)。看看this ticket。一个不太优雅的快速修复是在您的更新方法中加载您的关联:

@post = Post.includes(:attachments).find(params[:id])

if @post.update_attributes(params[:post])
  redirect_to(posts_url, :notice => 'Post updated.'
else
  render :action => "edit"
end

仅供参考,Rails 3.0.4仍然需要这样做。