我有三个模型
Tag=>:id,:nameTagging=>:id,:tag_id,:post_idPost=>:id,:summary
我知道标签的ID。我想tag_id通过Taggings模型查询所有具有特定 , 的帖子。
就像是
@post = Post.joins(:taggings).where(:tag_id => 17)
但这不起作用,因为它正在寻找模型中的 tag_idPost而不是Tagging模型。
我不知道该怎么做。
我有三个模型
Tag=> :id,:nameTagging=> :id, :tag_id,:post_idPost=> :id,:summary我知道标签的ID。我想tag_id通过Taggings模型查询所有具有特定 , 的帖子。
就像是
@post = Post.joins(:taggings).where(:tag_id => 17)
但这不起作用,因为它正在寻找模型中的 tag_idPost而不是Tagging模型。
我不知道该怎么做。
我不喜欢在 ActiveRecord 查询中使用字符串,所以,我更喜欢这个 sintax:
@post = Post.joins(:taggings).where(taggings: {tag_id: 17})
首先 :
class Post < ActiveRecord::Base
has_many :taggings
has_many :tags, :through => :taggings
end
class Taggins < ActiveRecord::Base
belongs_to :post
belongs_to :tag
end
class Tag < ActiveRecord::Base
has_many :taggings
has_many :posts, :through => :taggings
end
如果你有标签对象,你可以做
@posts = @tag.posts
或者
class Post < ....
....
def self.find_by_tag_id(tag_id)
Post.joins(:taggings).where('taggings.tag_id = ?', tag_id)
end
end
使用 .where 格式,您可以传递类似 .where("taggings.tag_id = ?", 17) 的字符串来限定连接的标记表。
正如@tharrison 提到的。一个解决方案是:
@post = Post.joins(:taggings).where("taggings.tag_id = ?", 17)