Saturday 30 August 2014

Multi-select dropdown with has many through association in rails

Lets consider you have a brand and a brand can be in multiple states.
And therefore to create a brand you want to select multiple states in which that brand exists.

Brands and states are associated with a has_many through association.

Here is your models:

state model:

class State < ActiveRecord::Base
  attr_accessible :name
   has_many :brand_states
  has_many :brands, through: :brand_states

end

brand model(note state_ids in attr_accessible):

class Brand < ActiveRecord::Base
attr_accessible :name,:state_ids     

end

brand_state model

class BrandState < ActiveRecord::Base
  belongs_to :brand
  belongs_to :state
end


Your form for new and edit:

<%= simple_form_for @brand, :html => { :class => 'form-horizontal', :multipart => true }  do |f| %>
  <%= f.input :name, :as => :string %>

    <div class="field ">
      <%= f.label :states, "Select States" %>
      <%= f.collection_select(:state_ids,State.all, :id, :name,{},:multiple => true) %>
    </div>  

<% end %>

Controllers:
Everything will be same no changes for multiselect dropdown.

And thats it  you are done!