Sql 如何使用多态has#u one关联查询';s属性?
我正在使用多态关联来论证我的Sql 如何使用多态has#u one关联查询';s属性?,sql,ruby-on-rails,activerecord,Sql,Ruby On Rails,Activerecord,我正在使用多态关联来论证我的Post模型(它具有常见的Post属性title、body、date等…) 这是我的模型 class Post < ActiveRecord::Base belongs_to :post_module, polymorphic: true end class Album < ActiveRecord::Base has_one :post, as: :post_module belongs_to :artist end class Arti
Post
模型(它具有常见的Post属性title、body、date等…)
这是我的模型
class Post < ActiveRecord::Base
belongs_to :post_module, polymorphic: true
end
class Album < ActiveRecord::Base
has_one :post, as: :post_module
belongs_to :artist
end
class Artist < ActiveRecord::Base
has_many :albums
end
现在我想查询Post
s,它有一个与该帖子相册的艺术家id相同的专辑模型
我可以查询与
@post
相册具有相同艺术家id的相册
模型。。。但那不是我想要的
我想要一套Post
@albums = Album.where('albums.artist_id = "?"', @post.post_module.artist.id)
我该怎么做?还是我在设计一个糟糕的模特关系?为一个艺术家发帖
artist = Artist.last
#This will get a scoped object for all posts belonging to this artist's albums
posts = Post.where(id: artist.albums)
对于模型设计,有两个建议:
postable
而不是post\u模块
如果我理解正确,您希望检索给定艺术家id的所有帖子。因此:
@posts = Post.joins(:post_module => :album).where(:post_module => { :album => { :artist_id => artist_id }})
我最终得到了
Post.joins('albums.id=posts.Post_module_id')。其中('posts.Post_module_type=“Album”和albums.artist_id=“?”,@artist.id)
它不适用于带有NameError的错误:未初始化常量Post::PostModule
@posts = Post.joins(:post_module => :album).where(:post_module => { :album => { :artist_id => artist_id }})