ActiveRecord接受_ented_attributes和回调

时间:2012-12-06 23:48:10

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

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

class Author < ActiveRecord::Base
  belongs_to :post
end

class Comment < ActiveRecord::Base
  attr_accessible :disabled
  belongs_to :post
  before_create :set_disabled

  def set_disabled
    if self.post.authors.first.name == "Foo"
      self.disabled == true
    end
  end
end

使用嵌套属性创建新帖子

params = {
  post: {
    title: "A New Post", 
    comments_attributes: [
      { body: "This is a great post" }
    ], 
    authors_attributes: [
      {name: "Foo"}
    ]
  }
}

a = Post.create(params)

我们在set_disabled回调中收到错误,因为评论无法访问post.authors,即使它们在内存中也是如此。

我们目前的解决方案是将其从ObjectSpace中删除。必须有更好的方法来做到这一点吗?

2 个答案:

答案 0 :(得分:0)

我不确定你是否会从另一方获得更好的运气(我现在无法测试这个),但是如果从Post尝试这个呢?本身:

class Post < ActiveRecord::Base
  # your associations ...

  before_create do
    comments.each do |c|
      c.disabled = true
    end if authors.first.name == "Foo"
  end
end

答案 1 :(得分:0)

您的模型只需稍加改动即可。只需在关联

之后添加nested_attributes
class Post < ActiveRecord::Base
  has_many :comments
  has_many :authors
  accepts_nested_attributes_for :comments
  accepts_nested_attributes_for :authors

  attr_accessible :comments_attributes, :authors_attributes, :title .....

end