Search code examples
ruby-on-rails-3activeadminformtastic

ActiveAdmin Form not respecting :multiple => false


I'm using ActiveAdmin and trying to do a as: :select, :collection that isn't a multiple select.

My code is:

form do |f|
  f.input :users, :as => :select, :input_html => { :size => 1}, :multiple => false, collection: User.where(role:1), include_blank: false
end

Where this is in /admin/businesses.rb. The relationship is that there is habtm between Users and Businesses. I've tried rearranging my options as shown in the github issue. I've also looked at a similar stackoverflow question.

However, when I try with the :multiple => false, I get this code generated:

<select id="business_user_ids" multiple="multiple" name="business[user_ids][]" size="1">    
<option value="4">Pilgrim</option>
<option value="5" selected="selected">Mary</option>
<option value="6" selected="selected">Bob</option>
<option value="7">Billy</option>
<option value="8">Ash</option></select>

Note that there are two selected, and the code for multiple is set to multiple. Any one know why this is?

Also, I'm trying to figure out how to display another field as what is selectable.

For example, I have f.inputs :users. is there a way to rename what is shown for :users? Right now, it shows users.name, but I would like users.email.


Solution

  • I just bumped into this problem, too. After a little code tracing I found that it's duo to the underlying Formtastic lib.

    Formtastic takes precedence of existing reflection (has_many & has_and_belongs_to_many) over the options you pass in to decide it's multiple or not.

    I think it's because forcing single selection on a ?-to-many relation will cause some confusions. Just like your data, there are already two selected, what should be shown in a strict single select? But I'll maybe raise this issue to Formtastic later.

    If you still need that function, you could just monkey patch it by placing the following code at config/initializers/formtastic.rb

    module Formtastic
      module Inputs
        class SelectInput
          def multiple_with_options_fix?
            return false if options[:multiple] === false
            multiple_without_options_fix?
          end
    
          alias_method_chain :multiple?, :options_fix
        end
      end
    end
    

    And for your second question, you just need to add the following code into your model.

    class User < ActiveRecord::Base
      .....
    
      def to_label
        self.email
      end
    end