2012-11-07 143 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