thoughtbot / administrate

A Rails engine that helps you put together a super-flexible admin dashboard.
http://administrate-demo.herokuapp.com
MIT License
5.88k stars 1.11k forks source link

Scope select options to a particular resource? #2459

Open wengzilla opened 10 months ago

wengzilla commented 10 months ago

I would like to scope a BelongsTo field to a particular set of things based on the resource, but I'm not sure how to achieve this...

Right now, I have the following relationship: Companies have many Departments which have many Employees. Or, in other words, Employee belongs to a Department which belongs to a Company.

I want to have a field on my EmployeeDashboard that looks as follows:

ATTRIBUTE_TYPES = {
    departments:
      Field::BelongsTo.with_options(scope: ->(resource) { resource.company.departments }),
  }.freeze

I could monkey patch the scope call to pass in resource, but is there a more elegant way to do this?

Nitr commented 4 months ago

@wengzilla I have the same issue, you can monkey patch BelongsTo like this:

def candidate_resources
  scope = if options[:scope]
    options[:scope].arity.positive? ? options[:scope].call(self) : options[:scope].call
  else
    associated_class.all
  end

  order = options.delete(:order)
  order ? scope.reorder(order) : scope
end

then in your dashboard:

ATTRIBUTE_TYPES = {
    departments:
      Field::BelongsTo.with_options(scope: ->(field) { field.resource.company.departments }),
  }.freeze

Another solution is to use Select:

ATTRIBUTE_TYPES = {
    departments:
      Field::Select.with_options(collection: ->(field) { field.resource.company.departments.pluck(:name, :id) }),
  }.freeze
benoror commented 1 month ago

Nice @Nitr , this should be by default