ruby on rails - saving array output into a join table (unpermitted parameter) -


the event saved, "artists":[] blank, though selected multiple artists in new form. relevant part of new form looks this:

  <%= f.fields_for :event_artists |fea| %>     <%= fea.collection_select :artist_id, artist.all, "id", "name", {include_blank: true}, {multiple: true} %>   <% end %> 

the log:

  parameters: {"utf8"=>"✓", "authenticity_token"=>"oeh0j/cp35s/fabhsetxeqknqzckxrbzmpeeee6p+ksm3qvf94zilub1rqad65ci5cp+r6tqs8v1f3sxiq6vtw==", "event"=>{"name"=>"", "date(1i)"=>"2016", "date(2i)"=>"7", "date(3i)"=>"22", "date(4i)"=>"01", "date(5i)"=>"55", "description"=>"", "venue_id"=>"1", "event_artists_attributes"=>{"0"=>{"artist_id"=>["", "1", "2"]}}}, "commit"=>"create"} unpermitted parameter: artist_id 

here parameter permitted in controller

def event_params   params.require(:event).permit(:id, :name, :date, :venue_id, :description, { event_artists_attributes: [:artist_id] }) end 

event_artist model looks this:

class eventartist < applicationrecord   belongs_to :event, optional: true   belongs_to :artist end 

event model:

class event < applicationrecord   belongs_to :venue   has_many :event_artists   has_many :artists, through: :event_artists   accepts_nested_attributes_for :event_artists, reject_if: :all_blank, allow_destroy: true  end 

event controller:

  def create     @event = event.new(event_params)      if @event.save       render json: @event, status: :created, location: @event     else       render json: @event.errors, status: :unprocessable_entity     end   end    def new     @event = event.new     @artist = @event.event_artists.build   end 

you have event_artists_attributes inside of unnecessary hash. instead, use:

  params.require(:event).permit(:id, :name, :date, :venue_id, :description, event_artists_attributes: [artist_id]) 

but have problem. you're trying set multiple artist ids on eventartist belongs_to 1 artist. because have has_many artists, through: :event_artists on event model, can change following:

controller:

def event_params   params.require(:event).permit(:id, :name, :date,                                  :venue_id, :description, artist_ids: []) end 

and in form, remove <%= fields_for… block , replace with:

<%= f.collection_select :artist_ids, artist.all, "id", "name",                            {include_blank: true}, {multiple: true} %> 

Comments