2012-11-07 146 views
1

我有三个型号导轨联接查询

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

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

喜欢的东西

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

,而是因为它正在寻找在Post模型TAG_ID而不是Tagging模型中,这是行不通的。

我不知道如何做到这一点。

+0

您是否在Post模型中设置了以下'has_many:tags,:through =>:tagging'? – MrYoshiji

+0

使用'.where'格式,您可以传递像'.where(“taggings.tag_id =?”,17)'这样的字符串来限定加入的标记表。 –

+0

@MrYoshiji是的,我有。 – ebbflowgo

回答

2

使用。凡格式可以传递等。凡字符串来限定连接的Tagging表(,17“taggings.tag_id =?”)。

1

正如@tharrison所述。一种解决方案是:

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

这里只是一个注释 - 第一个'标记'需要单数,否则你会得到错误:'协会命名未找到可能拼写错误的问题在rails协会参考:http://stackoverflow.com/questions/19231629/association -named-not-found-maybe-not-spelling-issue-in-rails-association – gwalshington

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 
8

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

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

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