问题
I am using Active Admin in my multi tenant app. I also use Searchkick which has a custom tenant specific index in each model:
class Budget < ApplicationRecord
multi_tenant :company
searchkick inheritance: true,index_name: -> { [MultiTenant.current_tenant.tenant_name, model_name.plural, Rails.env].join('_') }
end
The issue is that in AA this logic fails because on the tenant is set. I want to be able to set this in AA when updating a record.
For example I would update http://localhost:4000/admin/budgets/dt2kqvgm where dt2kqvgm
is the Friendly ID of the record. So I want to call something like:
MultiTenant.current_tenant = Budget.friendly.find(params['budget']['company_id'])
when I create / update a record etc.
Currently I get:
undefined method `tenant_name' for nil:NilClass
because in my application controller the tenant is set based on the user authentication to scope the current company etc. In AA I want/ need to set this based on the params which it seems you can't access from the AA controller logic. My params look like this in AA:
{"utf8"=>"✓", "_method"=>"patch", "authenticity_token"=>"PrhNGnPvV1Qfb5RCwTVv4Wwz9tjf9SFy2VWDcyJXoFLytM8y5ZAyF7h8I7xa+fy01E9Fc/v2CvR52I4/LKOLHQ==", "budget"=>{"company_id"=>"9", "name"=>"qweqwe", "description"=>"qweqwe", "notes"=>"qwee", "flag_active"=>"1", "slug"=>"dt2kqvgm", "title"=>"qweqwe"}, "commit"=>"Update Budget", "controller"=>"admin/budgets", "action"=>"update", "id"=>"dt2kqvgm"}
回答1:
I don't know if this is the best way to do this but it works. I am know it needs tweaks but it's a start - you needs to:
- set an
around_action
filter - add permitted_params
around_action :set_tenant, only: :update controller do def set_tenant MultiTenant.with(Company.find(resource.company_id)) do yield end end def permitted_params params.permit location: %[ company_id ] end end
It would seem this is required for each controller. Perhaps there is a way to add this as a default AA filter?
I also added the filter to just the update
action.
来源:https://stackoverflow.com/questions/63697727/set-multi-tenant-in-active-admin-controllers-required-for-searchkick-index