類ActiveRecord的accepts_nested_attributes和回調
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)
因爲意見無法訪問,即使他們」的post.authors
我們得到的set_disabled
回調錯誤記憶中。
我們目前的解決方案是抓住他們出ObjectSpace
。必須有更好的方法來做到這一點?
您得到的錯誤究竟是什麼?關於你的方法*(檢查'before_create'中的關係)*只是**感覺錯誤。 – deefour
另外,如果將'set_disabled'的回調更改爲'after_create',會發生同樣的錯誤*(不管它是什麼)*?你需要再次在模型上調用'save',但我很好奇。 – deefour
我沒有嘗試使用'after_create'。所有這些都需要一起保存。全部或全無。錯誤是它不能調用'nilClass'沒有方法'name'。 'post.authors'在這一點上是一個空白數組,所以這是有道理的。 – mehulkar