Search code examples
ruby-on-railsruby-on-rails-4nested-formsnested-attributes

Form helpers for nested attributes has_many through in rails 4


I have 3 models with has_many through association:

class Spot < ActiveRecord::Base
  has_many :seasons
  has_many :sports, through: :seasons
  accepts_nested_attributes_for :sports, :seasons
end

class Sport < ActiveRecord::Base
    has_many :seasons
    has_many :spots, through: :seasons
end

class Season < ActiveRecord::Base
  belongs_to :spot
  belongs_to :sport

end

I want to create a form so that editing the Spot you can create/edit Season for particular Sport.

I've got it working this way:

= form_for([@country, @spot], :html => { :multipart => true }) do |f|

#some Rails code here

  = f.fields_for :seasons do |builder|
    = builder.select :sport_id, options_from_collection_for_select(Sport.all, :id, :name, :sport_id)
    = builder.text_field :months
    = builder.hidden_field :spot_id

However it doesn't mark any Sport as "selected". I don't know what to substiture ":sport_id" for in the options.

I've got it working properly without Rails form helpers, but it seems that could be done with helpers:

  - @spot.seasons.each do |season| 
    = select_tag "spot[seasons_attributes][][sport_id]", options_from_collection_for_select(Sport.all, :id, :name, season.sport.id)
    = hidden_field_tag 'spot[seasons_attributes][][id]', season.id
    = text_field_tag 'spot[seasons_attributes][][months]', season.months

Thanks in advance, Vadim


Solution

  • Use collection_select helper on a form builder.

    builder.collection_select(:sport_id, Sport.all, :id, :name)