问题
I have models User, Tagging, Tag
User.rb
has_one :tagging
Tagging.rb
belongs_to :user
belongs_to :tag
Tag.rb
has_many :taggings
I want to scope the User based on the Tag's name. How to do it?
Currently, I know how to do the scope under one level association, for example:
scope :with_tag_id, -> (tag_id) {joins(:tagging).where(taggings: {tag_id: tag_id})}
But how to do more levels?
回答1:
Try this
class User < ActiveRecord::Base
scope :by_tag_name, ->(tag_name) { joins(tagging: :tag).where("tags.name=?", tag_id, tag_name)
end
来源:https://stackoverflow.com/questions/34715101/how-to-scope-model-through-two-level-association-in-rails