如何获得与模型相关模型相关的模型?

时间:2013-03-04 05:29:25

标签: ruby-on-rails

我有两个模特。

 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

现在假设我有Article与两个Artist相关(例如Michael Jackson,Beatles ......)

然后每个艺术家都有一些文章。

我想要做的是通过Article提取与artists相关的所有文章

这是我尝试的东西(不起作用......)

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:1)

您没有为ArtistRelationship模型发布代码,但我假设您使用以下内容完成了has_many_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