Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/sql/84.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Sql 如何使用多态has#u one关联查询';s属性?_Sql_Ruby On Rails_Activerecord - Fatal编程技术网

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) 
对于模型设计,有两个建议:

  • 若只有相册将与Post相关联,就不需要多态,尽管我猜你们可能会有更多
  • 对于多态名称,约定是使用adj、
    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 }})