Rails连接查询

3

我有三个模型

  • 标签 (Tag) => :id, :name
  • 标签关联(Tagging) => :id, :tag_id, :post_id
  • 文章(Post) => :id, :summary

我知道标签的 id,我想通过 标签关联(Tagging) 模型查询拥有特定 tag_id 的所有文章。

类似于下面这样:

@post = Post.joins(:taggings).where(:tag_id => 17)

但是这样不起作用,因为它在Post模型中查找tag_id而不是Tagging模型中查找。

我不确定该如何解决这个问题。


你在Post模型上设置了以下的has_many :tags, :through => :tagging吗? - MrYoshiji
使用.where格式,您可以传递类似.where("taggings.tag_id = ?", 17)的字符串来限定连接的 taggings 表。 - Tom Harrison
@tharrison 太好了,谢谢!如果你发表一个答案,我会选择它。 - 1dolinski
4个回答

17

我不喜欢在ActiveRecord查询中使用字符串,因此我更喜欢这种语法:

@post = Post.joins(:taggings).where(taggings: {tag_id: 17})

2
如果需要的话,您还可以在标记后添加其他条件.where(taggings: {tag_id: 17}, tags: {valid: true}) - icantbecool

7

首先:

 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

2
使用.where格式,您可以传递一个类似于.where(“taggings.tag_id =?”,17)的字符串来限定连接的taggings表。

1

正如@tharrison所提到的,一个解决方案是:

@post = Post.joins(:taggings).where("taggings.tag_id = ?", 17)

1
这里只是一个小提示 - 第一个 'taggings' 需要是单数形式,否则你会得到错误:association named not found perhaps misspelled issue in rails association 参考链接:https://dev59.com/zWIk5IYBdhLWcg3we-L5 - gwalshington

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接