Search code examples
ruby-on-railsrubyruby-on-rails-4activeadminrails-admin

Want to be able to set the default field values that should be shown in a multi-select list rails_admin


I have the following model

class Campaign < ActiveRecord::Base
  has_many :campaign_rules
  has_many :campaign_details
  validates_presence_of [:start_at, :end_at]

  rails_admin do
    edit do
      field :slug
      field :start_at
      field :end_at
      field :is_active
      fields :campaign_rules do
        searchable :slug
      end
      fields :campaign_details
    end
  end
end

in my view, i get the following when i want to say create a new campaign. enter image description here

But in my campaign_rules model, i have a field called slug which i would prefer to be shown as the default text in the associated record in the multi-select list. So for example for CampaignRule #1 , slug name is campaign-1 and i would prefer in my multi-select list to show campaign-1 instead of CampaignRule #1.

How can i do this?

I also want to be able to make sure that the multi-select dropdown list shown is based on associated campaign_id. Currently in my multi-select dropdown, it shows all records of the CampaignRule even though there is an association with campaign. How do i configure this as well?


Solution

  • By default rails admin uses the name attribute of an instance to display them.

    You can tell rails admin what method to use adding this line on the initializer config file.

    RailsAdmin.config {|c| c.label_methods << :rails_admin_title }
    

    And then you would implement that instance method on your tag model

    class CampaignRaule < ApplicationRecord
       def rails_admin_title
          self.slug
       end 
    end
    

    As to how customize the records on the multi-select dropdown you can filter them with a regular ActiveRecord scope like this:

    class Campaign < ApplicationRecord
      rails_admin do
        edit do
          field :campaign_rules do
            associated_collection_scope do
              associated_collection_scope do
                campaign = bindings[:object]
    
                proc { |scope| scope.where(campaign: campaign) }
              end
            end
          end
        end
      end
    end