2013-03-04 177 views
0

我有兩種模式。如何獲取與模型關聯模型相關的模型?

文章

class Article < ActiveRecord::Base 

    attr_accessible :title, :body, :artist_ids 

    has_many :artists, :through => :artist_relationships 
    has_many :artist_relationships 

end 

Artist.rb

class Artist < ActiveRecord::Base 

    attr_accessible :title, :body, :article_ids 

    has_many :articles, :through => :artist_relationships 
    has_many :artist_relationships 

end 

現在假設我有兩個Artist相關的Article(如邁克爾·傑克遜,披頭士......)

那麼每個藝術家都有一些文章給他們。

我想要做的是通過其artists獲取所有文章Article有關..

這是什麼東西我想(這是行不通的....)

@article = Article.find(param[:id]) # an Article 
@articles = Article.where(:artist_ids => @article.artist_ids) # get all articles of its related artists 

回答

1

嘗試

@articles = Article.joins(:artist_relationships).where(artist_relationships: { artist_id: @article.artist_ids }) 
+0

謝謝您的回答。它工作正常,除了有關兩位藝術家的文章出現兩次。我該如何解決它? – synthresin 2013-03-04 05:40:29

+0

我通過附加'''.uniq'''解決了這個問題,謝謝! – synthresin 2013-03-04 05:45:31

1

你沒有發佈您的代碼爲您ArtistRelationship模型,但我相信你完成了has_man使用y_through關係:

class ArtistRelationship < ActiveRecord::Base 
belongs_to :article 
belongs_to :artist 
end 

如果您在本設置正確,那麼你就可以利用的方法,如@article.artists@artist.articles

所以,你可以做線沿線的東西:

@article = Article.find(params[:id]) #Any given article 
@artists = @article.artists #All artists related to the article 
@articles = @artists.collect{|artist| artist.articles} #Collection of all articles related to all the artists 
+0

我會檢查收集方法。謝謝! – synthresin 2013-03-04 06:39:09

相關問題