0

班级

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. 必须有更好的方法来做到这一点?

4

2 回答 2

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
于 2012-12-07T05:03:40.000 回答
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
于 2012-12-07T02:12:33.717 回答