Search code examples
ruby-on-railstwitter-bootstrapassociationssimple-formmulti-select

How do I create/remove objects to an association through my Rails form?


I'm wanting to add/remove records to an association from my main form object Report. I have my multiselect drop-down list showing correctly and passing ids correctly to my update action. However, I'm receiving the following message.

Couldn't find all ReportExposures with 'id': (157504, 148644, 152852) (found 0 results, but was looking for 3)

Now I know that those ids are actually my ncaa_game_ids I'm wanting to assign to the ReportExposure record, but I can't put the ReportExposure id because it doesn't really exist yet. What do I need to tweak on my form to get this to work correctly, or do I need to add some code in my update action to handle these?

Report.rb

class Report < ActiveRecord::Base
  has_many :report_exposures
end

ReportExposure.rb

class ReportExposure < ActiveRecord::Base
  belongs_to :ncaa_game
  belongs_to :report
end

ReportsController.rb

def update

  # "report_exposure_ids"=>["157504","148644","152852"] -- these ids are really the ncaa_game_ids I want to create new report_exposure objects with...

  respond_to do |format|
    if @report.update(report_params)
      format.html
      format.json
    end
  end

end

_form.html.erb

<select id="report_report_exposure_ids" name="report[report_exposure_ids][]" class="multiselect-dropdownlist" multiple="multiple">
  <% @exposures.each do |season| %>
    <optgroup label="<%= season.first.season %> Season">
      <% season.includes(:home_team, :away_team).order(game_date: :asc).each do |game| %>
        <option value="<%= game.id %>"><%= game.full_description %></option>
      <% end %>
    </optgroup>
  <% end %>
</select>


Solution

  • Change reports to this:

    class Report < ActiveRecord::Base
      has_many :report_exposures
      has_many :ncaa_games
      accepts_nested_attributes_for :ncaa_games
    end
    

    And read about doing nested forms here:

    http://guides.rubyonrails.org/form_helpers.html#nested-forms

    There are a lot of examples of people asking questions about nested_forms with a has_many through relationship. Take a look at those for guidance:

    Rails has_many :through nested form

    Don't try to manipulate the join object (ReportExposure) unless you are actually dealing with adding metadata to that object. That is what the ORM is for.