2012-12-06 34 views
0

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。必須有更好的方法來做到這一點?

+0

您得到的錯誤究竟是什麼?關於你的方法*(檢查'before_create'中的關係)*只是**感覺錯誤。 – deefour

+0

另外,如果將'set_disabled'的回調更改爲'after_create',會發生同樣的錯誤*(不管它是什麼)*?你需要再次在模型上調用'save',但我很好奇。 – deefour

+0

我沒有嘗試使用'after_create'。所有這些都需要一起保存。全部或全無。錯誤是它不能調用'nilClass'沒有方法'name'。 'post.authors'在這一點上是一個空白數組,所以這是有道理的。 – mehulkar

回答

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 
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 
+0

我沒有意識到訂單的重要性。但是我的實際代碼實際上在關聯之後有'accep_nested_attributes_for'。儘管'attr_accesssible'聲明在中間。我會編輯並回復你。 – mehulkar