Rails加入查询

1do*_*ski 2 postgresql activerecord ruby-on-rails ruby-on-rails-3

我有三个型号

  • Tag=> :id,:name
  • Tagging=> ,,:id:tag_id:post_id
  • Post=> :id,:summary

我知道标签的ID.我想tag_id通过Taggings模型查询具有特定内容的所有帖子.

就像是

@post = Post.joins(:taggings).where(:tag_id => 17)
Run Code Online (Sandbox Code Playgroud)

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

我不知道该怎么做.

小智 15

我不喜欢在ActiveRecord查询中使用字符串,所以,我更喜欢这个sintax:

@post = Post.joins(:taggings).where(taggings: {tag_id: 17})
Run Code Online (Sandbox Code Playgroud)

  • 您还可以根据需要在标签后添加其他条件。.w​​here(taggings:{tag_id:17},tags:{valid:true}) (2认同)

小智 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
Run Code Online (Sandbox Code Playgroud)

如果你有标签对象,你可以做

 @posts = @tag.posts 
Run Code Online (Sandbox Code Playgroud)

要么

 class Post < .... 
   ....
   def self.find_by_tag_id(tag_id)
      Post.joins(:taggings).where('taggings.tag_id = ?', tag_id)
   end
 end
Run Code Online (Sandbox Code Playgroud)