-->

Scoping an association search with Ransack

2019-07-09 16:01发布

问题:

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.

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).

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.

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.

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])

but with out success.

回答1:

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

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}'") }

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.

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.