使用Ransack设定关联搜索范围 [英] Scoping an association search with Ransack

查看:81
本文介绍了使用Ransack设定关联搜索范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 User 模型和一个与之关联的注册模型。一个用户可以有许多注册,但每个注册只有一个公司

I have a User model with an Enrollment model associated with it. A User can have many Enrollments but each Enrollment only has one Company.

我的注册模型具有 flag_contractor 布尔值。因此,如果我有一个 User 搜索,例如:enrollment_flag_contractor false ,则在尝试确定范围时,我会得到不一致的结果当前公司的注册(通过Apartment gem)。

My Enrollment model has a flag_contractor boolean. So if I have a User search such as :enrollment_flag_contractor false I can get inconsistant results as I am trying to scope my enrolments for the current company (via the Apartment gem).

例如,我有一个用户在两个独立的公司中注册,其中一个公司的flag_contractor = true,另一个公司的flag_contractor = false。

For example I have a user that has an enrollment in two separate companies, one with flag_contractor = true and one with flag_contractor = false.

我已经将 User 模型的范围限定为仅在当前公司中拥有注册用户但是Ransack似乎仍会在关联中进行深入研究并搜索所有注册内容。

I have already scoped the User model to only have the Users with enrollments in the current company but Ransack seems to still drill down in the association and search across all the enrollments.

我试图将Ransack范围添加到我的 Enrollment 模型:

I have tried to add a Ransack scope to my Enrollment model:

scope :active, -> (company_id) { where(company_id: company_id) }

然后修改了我的用户控件:

then modified my Users controler:

@users = @search.result(distinct: true, active: current_company.id).paginate(:page => params[:page])

但未成功。

推荐答案

我认为这可能是最好的答案,因为这是做到这一点的唯一方法(也许是最好的方法)。

I think this may be the best answer as it's the only way (and may be the best) to do this.

这是我在 User 模型中现在拥有的范围:

Here are the scopes I now have in my User model:

scope :enrolled_old, -> { joins(:companies).where("companies.tenant_name = '#{Apartment::Tenant.current}'") }
scope :enrolled, -> (company_id) { joins(:enrollments).where("enrollments.company_id = '#{company_id}'") }

旧的没有用。不知道为什么。如果我将company_id传递给范围,则范围将起作用。

The old one didn't work. Not sure why. If I pass the company_id into the scope the scope works. They seemed to both work from the console.

因此,在我的Pundit用户策略中,我已经:

So now in my Pundit User policy I have:

company = Company.where(tenant_name: Apartment::Tenant.current).last
User.joins(:enrollments).where("enrollments.company_id = '#{company.id}'")

这有效,并且实际上有助于更好地锁定我的政策。

That works and it actually helps lock down my Policy better.

这篇关于使用Ransack设定关联搜索范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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