【发布时间】:2012-12-06 23:48:09
【问题描述】:
类
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 中获取它们。一定有更好的方法来做到这一点?
【问题讨论】:
-
你得到的错误究竟是什么?您的方法(检查
before_create中的关系)只是感觉错误。 -
另外,如果将
set_disabled的回调更改为after_create,是否会出现同样的错误(无论它是什么)?您需要再次致电模型上的save,但我很好奇。 -
我没有尝试使用
after_create。所有这些都需要一起保存。全有或全无。错误是它不能调用nilClass没有方法name。post.authors在这一点上是一个空白数组,所以这是有道理的。
标签: ruby-on-rails activerecord ruby-on-rails-3.2