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