如何在Rails中通过两级关联对模型进行范围划分? [英] How to scope model through two level association in Rails?

查看:81
本文介绍了如何在Rails中通过两级关联对模型进行范围划分?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下模型:用户标记标记

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?

推荐答案

尝试一下

class User < ActiveRecord::Base

   scope :by_tag_name, ->(tag_name) { joins(tagging: :tag).where("tags.name=?", tag_id, tag_name)

end

这篇关于如何在Rails中通过两级关联对模型进行范围划分?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆