Search code examples
ruby-on-railsactiverecordnested-formswhitelist

Nested whitelisted attributes still unpermitted


I have three models: event, event_user, event_users_day.

event accepts nested attributes event_user which accepts event_users_day as a nested attributes as well.

class Event < ActiveRecord::Base
  has_many :event_users, :dependent => :destroy, :inverse_of => :event
  accepts_nested_attributes_for :event_users, :allow_destroy => true
end

class EventUser < ActiveRecord::Base
  belongs_to :event, :inverse_of => :event_users
  has_many :event_users_days, :dependent => :delete_all
  accepts_nested_attributes_for :event_users_days, :allow_destroy => true
end

class EventUsersDay < ActiveRecord::Base
  belongs_to :event_users, inverse_of: :event_users_days
  validates :event_users, :presence => true
end

The simple nested form is pretty straight forward:

= simple_nested_form_for :event_users do |f|
  = f.fields_for :event_users_days do |day|
    = day.input :event_day_id, as: :check_boxes, collection: @daygroups
= f.submit :class => "btn btn-success"

In my controller event_user and the attributes for event_users_days are whitelisted:

    @event_user = EventUser.new(params.permit(:event_id), params[:event_users].permit(:id, event_users_days_attributes: [:id, :event_day_id]))

But when I save it only the EventUser is saved as the server tells me that event_users_days is not permitted:

Unpermitted parameter: event_users_days

Any ideas of what am I doing wrong?


Solution

  • The Unpermitted parameter error is being literal, so your form is generating a event_users_days parameter instead of the expected event_users_days_attributes parameter, which is being rightly rejected by Rails.

    I haven't used nested_form in a long time, and if you're using Rails 4 then I'm not sure that's going to be the best pick (and it's not necessary), but even so I think the problem is that you're using :event_users instead of @event_users - but generally I'd recommend switching to simple_form unless you're in an old Rails (and if you are then you should specify that when asking questions on SO).