2011-05-20 82 views
12

我有一些問題使用has_one, through => model。最好的是向你展示我的情況。has_one,:through => model VS簡單方法?

class Category 
    has_many :articles 
end 

class Article 
    has_many :comments 
    belongs_to :category 
end 

class Comment 
    belongs_to :article 
    has_one :category, :through => :articles 
end 

Everthing正常工作。我可以做comment.category。問題是,當我創建一個新評論並設置其文章時,我已經保存了評論以使協會有效。例如:

>> comment = Comment.new 
>> comment.article = Article.last 
>> comment.category 
    -> nil 
>> comment.article.category 
    -> the category 
>> comment.save 
>> comment.category 
    -> nil 
>> comment.reload 
>> comment.category 
    -> the category 

has_one, through => model反正不建立,構建構造函數和創建方法。所以,我想用我的評論模型替換:

class Comment 
    belongs_to :article 
    def category 
    article.category 
    end 
end 

聽起來不錯?

+0

人?沒有人有好的意見? – Hartator 2011-05-21 16:58:32

回答

6

沒有錯,你的想法。我看不到很多情況下has_one :category, :through => :articles是明顯更好的選擇(除非用Comment.all(:include => :category)急切加載)。

delegate一個提示:

class Comment 
    belongs_to :article 
    delegate :category, :to => :article 

一種不同的方法:

class Comment 
    belongs_to :article 
    has_one :category, :through => :article 

    def category_with_delegation 
    new_record? ? article.try(:category) : category_without_delegation 
    end 

    alias_method_chain :category, :delegation 
+0

有些更多的信息'alias_method_chain'可以在這裏找到(http://yehudakatz.com/2009/03/06/alias_method_chain-in-models/) – jigfox 2011-05-24 17:19:57

+0

好的很好的信息,放棄我的賞金給你。 – Hartator 2011-05-25 10:08:50

+0

我覺得這就是Rails默認應該做的事情......而不是隻是總是查詢數據庫,而是通過已經存在於內存中的對象! – pdobb 2016-03-01 19:39:59

2

儘量使你的類級的變化是這樣的:

class Category 
    has_many :articles 
    has_many :comments, :through => :articles 
end 
+0

對不起,我們在利益衝突中拼寫錯誤。不是我真正的應用程序的問題。 – Hartator 2011-05-20 10:43:13

相關問題