require 'administrate/field/belongs_to' require 'rails' module Administrate module Field class BelongsToSearch < Administrate::Field::BelongsTo class Engine < ::Rails::Engine initializer 'administrate-field-belongs_to_search.add_assets' do |app| app.config.assets.precompile << 'belongs_to_search.js' if app.config.respond_to? :assets Administrate::Engine.add_javascript 'belongs_to_search.js' if defined?(Administrate::Engine) end end def associated_class super end def belong_to_scope_place(current_user, model) puts model # model is Package # create a room need package reference model_variable = model.to_s.underscore.pluralize #=> places # so we scope the current user packages # methode send(...) t.ly/56cI if current_user.admin? || current_user.super_admin? scoped_model = model.all.pluck(:id) else scoped_model = current_user.send(model_variable).pluck(:id) end candidates = Place.find(*scoped_model) # => array of Places # but we need an activeRecordRelation and no an array # let transform that array to an activeRecordRelation here t.ly/2D0A candidates_activeRecord = Place.where(id: candidates.map(&:id)) # => Place::ActiveRecord_Relation [nil] + candidates_activeRecord.map do |resource| [display_candidate_resource(resource), resource.send(primary_key)] end end def associated_resource_options # candidate_resources is Place::ActiveRecord_Relation [nil] + candidate_resources.map do |resource| # resource is #=> Place [display_candidate_resource(resource), resource.send(primary_key)] end end end end end