Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HABTM association with Strong Parameters is not saving user in Rails 4

User model:

has_and_belongs_to_many :events

Event model:

has_and_belongs_to_many :users

Users controller:

params.require(:user).permit(:role, {:event_ids => []})

Events controller:

params.require(:event).permit(:subject, :location, :date, :time, :all_day, :reminder, :notes, {:users_ids => []})

My form:

<%= simple_form_for(@event) do |f| %>
    <%= f.input :subject %>
    <%= f.input :location %>
    <%= f.input :date %>
    <%= f.input :time %>
    <%= f.association :users %>
    <%= f.input :all_day %>
    <%= f.input :reminder %>
    <%= f.input :notes %>

    <%= f.button :submit, :class =>"btn btn-default" %>
<% end %>

I want to be able to choose a user from a list and save that user to the database. But I am getting the following message in my console when I try to create a new Event:

Unpermitted parameters: user_ids

Do I have my setup incorrect? Am I not passing in the correct instance variables to the form?

like image 684
Rav Johal Avatar asked Dec 06 '22 01:12

Rav Johal


2 Answers

Ugh...details details!

How it was previously:

params.require(:event).permit(:subject, :location, :date, :time, :all_day, :reminder, :notes, {:users_ids => []})

How it should be:

params.require(:event).permit(:subject, :location, :date, :time, :all_day, :reminder, :notes, {:user_ids => []})

Notice that :users_ids should actually be :user_ids!

like image 82
Rav Johal Avatar answered Dec 29 '22 11:12

Rav Johal


Or you can simply use shorthand syntax like this.

params.require(:event).permit(:subject, :location, :date, :time, :all_day, :reminder, :notes, user_ids: [])

Notice: user_ids: [] instead of {:user_ids => []}

like image 27
Ammar Shah Avatar answered Dec 29 '22 11:12

Ammar Shah