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:
- Commenting out the checkboxes associated with the Features model, the application will create and save the venue object properly.
- 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