2016-09-19 95 views
0

所以,下面是我的模型:ActiveRecord的查詢通過多個連接

post.rb

class Post < ActiveRecord::Base 
    has_many :taggings 
    has_many :tags, through: :taggings 
    has_many :collectables 
    has_many :collections, through: :collectables 
end 

tagging.rb

class Tagging < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :tag, counter_cache: :posts_count 
end 

tag.rb

class Tag < ActiveRecord::Base 
    has_many :taggings 
    has_many :posts, through: :taggings 
end 

collectable.rb

class Collectable < ActiveRecord::Base 
    belongs_to :post 
    belongs_to :collection, counter_cache: :posts_count 
end 

collection.rb

class Collection < ActiveRecord::Base 
    has_many :collectables 
    has_many :posts 
end 

一件收藏品有很多文章和帖子有很多標籤。現在我試圖創建一個搜索欄,將搜索收藏通過具有特定的帖子標籤tag.name是搜索字詞)。例如,集合1有一個標籤爲#cat的帖子。現在,如果用戶搜索「貓」,則收藏1將顯示在結果中。我不確定查詢應該如何實現這一點。

def self.search(search) 
    Collection.joins(:posts) ... ? 
end 
+0

'Collections.joins(posts::tags).where(tags:{name:search_term})' – omnikron

回答

1

試試這個:

def self.search(search) 
    Collection.includes(posts: :tags).where(tags: {name: search}) 
end 
-1

嘗試這個

def self.search(search) 
    Collection.joins(posts: :tags).where({tags: {name: search}}) 
end 

可以使用包括eager_load和加入,但是當你用加入那麼只有它會採取那些誰擁有的收藏品在所有其他情況下的帖子,它將採取所有具有帖子和沒有帖子的收藏。