我有两个模特。
第
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
答案 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