- 
                Notifications
    
You must be signed in to change notification settings  - Fork 2.3k
 
Has and belongs to many association
        Alexey edited this page Apr 29, 2016 
        ·
        8 revisions
      
    Synopsys:
For a multiselect widget: (natural choice for n-n associations)
class Team < ActiveRecord::Base
  has_and_belongs_to_many :fans
  attr_accessible :fan_ids
endOr for a nested form:
class Team < ActiveRecord::Base
  has_and_belongs_to_many :fans
  accepts_nested_attributes_for :fans, :allow_destroy => true
  attr_accessible :fans_attributes
  rails_admin do
    configure :fans do
      inverse_of :teams
      # configuration here
    end
  end
endThe other side of the association is as usual:
# for info
class Fan < ActiveRecord::Base
  has_and_belongs_to_many :teams
endThis will work for regular many-to-many relationships and self-referential many-to-manys.
For Rails 4+ don't need to use attr_accessible