2009-12-21 48 views
1

我目前在我的模型之一上使用嵌套模型質量分配。它工作的一種享受,但是,我希望能夠確保創建「belongs_to」同一用戶的任何嵌套模型。覆蓋嵌套模型質量分配的屬性

我已經設法通過使用別名法鏈接來實現這一點:

def contact_attributes_with_user_id=(attributes) 
    self.contact_attributes_without_user_id = attributes.merge("user_id" => user_id) 
    end 
    alias_method_chain :contact_attributes=, :user_id 

現在能正常工作,但它意味着我不再能保護屬性USER_ID上的接觸 - 這很容易趕上有人在未來。

任何人都可以想出更好的方法嗎?

回答

0

如果你添加一個before_save鉤到您Contact模型,就像這樣:

belongs_to :parent 
validates_presence_of :parent_id 

before_save :assign_user_id 

private 
def assign_user_id 
    self.user_id = parent.user_id 
end 

這樣你的聯繫人user_ids將跟隨父模型,你不必擔心在所有指定(你可以擺脫alias_method_chain)。

+0

好主意。我可以看到的一點點困難(並沒有反映在原始問題中)是我的聯繫人have_many:foos,而不是has_one - > belong_to。雖然我可以很容易地將它默認爲第一個foos user_id的值。 – Theozaurus 2009-12-22 10:52:28