所以,下面是我的模型: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
'Collections.joins(posts::tags).where(tags:{name:search_term})' – omnikron