Question

I have a Rails 4 application and am having problems creating a new record for a has_many :through association. A couple of observations that I made while debugging:

  1. Commenting out the checkboxes associated with the Features model, the application will create and save the venue object properly.
  2. The update action in the venues controller works fine for the feature checkboxes.

Can somebody tell me why my application is having problems saving the associated features object (an array) when creating a new venue? Not sure if this is because the foreign key, venue_id, doesn't exist prior to the save...

Here's the code:

venues.rb

class Venue < ActiveRecord::Base
  has_many :venue_features, dependent: :destroy
  has_many :features, :through => :venue_features

venue_features.rb

class VenueFeature < ActiveRecord::Base
  belongs_to :venue
  belongs_to :feature

features.rb

class Feature < ActiveRecord::Base
  has_many :venue_features, dependent: :destroy
  has_many :venues, :through => :venue_features

venues\new.html.erb (Features are listed as checkboxes - use selects relevant checkboxes)

<%= hidden_field_tag "venue[feature_ids][]", nil %>
<% Feature.all.each do |feature| %>
  <div class="checkbox">
    <label>
      <%= check_box_tag "venue[feature_ids][]", feature.id, @venue.feature_ids.include?(feature.id) %>
      <%= feature.name %><br>
    </label>
  </div>
<% end %>

venues_controller.rb

class VenuesController < ApplicationController
  def create
    @venue = Venue.new(venue_params)

    if @venue.save(venue_params)
      flash[:success] = "Success!"
      redirect_to venues_path
    else
      flash[:error] = "Problem!"
      render 'new'
    end
  end

  def venue_params
    params.require(:venue).permit(:attribute_1, :attribute_2, :feature_type_ids => [])
  end
end 
Was it helpful?

Solution

I'm sure there's a cleaner solution but what I ended up doing was to update a different set of strong parameters after a successful save. The problem prob has something to do with 1) one of my parameters, :feature_type_ids, is actually an array and/or 2) :feature_type_ids is in a different model (not the venues.rb). I thought that Rails would "automagically" handle saving to differnet models since venues.rb and features.rb have been set up through a :has_many :through relationship. I'd be curious for a better solution but the following works:

class VenuesController < ApplicationController
  def create
    ...
    if @venue.save(venue_only_params)
      if @venue.update_attributes(venue_params)
      flash[:success] = "Success!"
      redirect_to venues_path
    else
      flash[:error] = "Problem!"
    render 'new'
    end
  end

  def venue_params
    params.require(:venue).permit(:attribute_1, :attribute_2, :feature_type_ids => [])
  end

  def venue_only_params
    params.require(:venue).permit(:attribute_1, :attribute_2)
  end

end 
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top