How to scope model through two level association in Rails?

一曲冷凌霜 提交于 2019-12-11 23:20:23

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!