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

孤者浪人 提交于 2019-12-10 16:18:18

问题


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?


回答1:


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!




回答2:


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 => []}




回答3:


Attribute from simple_form: user_ids

Symbol in #permit: users_ids

You've added an s, remove that and you should be good to go as far as I can tell.




回答4:


In my case I had a Rails 3 installation before. I upgraded to Rails 4. The select just passed a string, not an association. Thus the syntax proposed did not work. I simply had to allow user_ids. I.e.:

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

It seems Rails 4 changed the behavior.



来源:https://stackoverflow.com/questions/24820249/habtm-association-with-strong-parameters-is-not-saving-user-in-rails-4

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!