接受嵌套属性&过滤器

时间:2012-09-19 14:20:45

标签: ruby-on-rails ruby-on-rails-3 activerecord ruby-on-rails-3.2

假设我有两个型号;邮政&评论

class Post < ActiveRecord::Base
  has_many :comments
  accepts_nested_attributes_for :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post

  before_save :do_something

  def do_something
    # Please, let me do something!
  end
end

我有一个Post表单,带有注释字段。除过滤器外,一切都按预期工作。使用上面的配置,不会触发注释上的before_save过滤器。

你能解释一下原因,以及我如何解决这个问题?

2 个答案:

答案 0 :(得分:1)

在这种情况下,Rails不会单独实例化并保存注释。最好在Post模型中添加一个回调来处理嵌套注释:

class Post < AR::Base
  before_save :do_something_on_comments
  def do_something_on_comments
    comments.map &:do_something
  end
end

答案 1 :(得分:0)

根据Bryan Helmkamp的说法,使用表单对象模式比使用accepts_nested_attributes_for更好。看看7 Patterns to Refactor Fat ActiveRecord Models

也许你可以做这样的事情?

class NewPost
  include Virtus

  extend ActiveModel::Naming
  include ActiveModel::Conversion
  include ActiveModel::Validations

  attr_reader :post
  attr_reader :comment

  # Forms are never themselves persisted
  def persisted?
    false
  end

  def save
    if valid?
      persist!
      true
    else
      false
    end
  end

private

  def persist!
    @post = Post.create!
    @comment = @post.comment.create!
  end
end

创建评论时会调用do_something。