Search code examples
ruby-on-railsrubyformsruby-on-rails-4nested-attributes

Rails nested attributes for many to many


Hi I am trying to implement a feature using nested attributes. In the form for creating a handicap (for Customer) I would like to display a list of all the Customer's leagues and when the form is submitted in the Create action, I would use @handicap.save and this will create the association between the Handicap and Leagues as well (the leagues that were selected in the form).

The only solution I found was without using nested attributes. In the new method I would get all the handicaps from customer and display them in the form. So when the form is submitted in the create action I would do validations.., create the @handicap record for Customer and then manually for each League Id that comes from the form I would create the associations.

#New/Create actions in the handicaps controller

def new
  @leagues = @customer.leagues
end

def create
  handicap = @customer.handicaps.build(handicap_params)
  if handicap.save
    associations = []
    params[:league_ids].each do |id|
      associations << LeagueHandicap.new(handicap_id: @handicap.id, league_id: id)
    end
    LeagueHandicap.import(associations)
  end
end

I would want to do handicap.save and automatically create the LeagueHandicap associations as well. However I have no clue on how to do it with nested attributes. Can it be done like this?

I have the following models:

class Customer < ActiveRecord::Base
  has_many :handicaps, dependent: :destroy
  has_many :leagues, dependent: :destroy
end

class Handicap < ActiveRecord::Base
  belongs_to :customer
  has_many :league_handicaps
  has_many :leagues, through: :league_handicaps, dependent: :destroy
end

class LeagueHandicap < ActiveRecord::Base
  belongs_to :handicap
  belongs_to :league
end

class League < ActiveRecord::Base
  has_many :league_handicaps
  has_many :handicaps, through: :league_handicaps, dependent: :destroy
end

(Many to many relationships between Handicap and League through LeagueHandicap)


Solution

  • If you permit league_ids rails should add them for you. You need to tell rails it's an array though

    def handicap_params
      params.require(:handicap).permit(league_ids: [])
    end