Rails: Unpermitted parameter in Rails 5
I had this issue when working on a Rails 6 application.
My application consists of a User
model that has a one-to-one relationship a Personal_Info
model
My original code was this:
User Model
class User < ApplicationRecord
has_one :personal_info, class_name: 'PersonalInfo', dependent: :destroy
accepts_nested_attributes_for :personal_info, allow_destroy: true
end
Personal Info Model
class PersonalInfo < ApplicationRecord
belongs_to :user
end
User Controller
class UsersController < ApplicationController
def index
@users = User.all
end
.
.
def user_params
params.require(:user).permit(:email, :password, :password_confirmation,
personal_info_attributes: [:first_name,
:last_name, :phone, :gender, :dob,
:address, :city, :state, :country])
end
end
The issue was that I did not add the Personal_Info id to the accepted user params (parameters).
Here's how I fixed it:
I simply had to add the Personal_Info id
to the UsersController params this way:
User Controller
class UsersController < ApplicationController
def index
@users = User.all
end
.
.
def user_params
params.require(:user).permit(:email, :password, :password_confirmation,
personal_info_attributes: [:id, :first_name,
:last_name, :phone, :gender, :dob,
:address, :city, :state, :country])
end
end
Another way is to add the update_only
option to the Users Model this way:
class User < ApplicationRecord
has_one :personal_info, class_name: 'PersonalInfo', dependent: :destroy
accepts_nested_attributes_for :personal_info, update_only: true, allow_destroy: true
end
That's all.
I hope this helps
It's not the inflection of the word "criteria" that's giving you problems (although you can add a custom inflector to get the singular and plural versions you prefer if you really want).
The issue is that you have to explicitly permit the fields of nested objects.
Change your current params:
params.require(:project).permit(:name, project_criteria: [] )
To this (for a single nested object):
params.require(:project).permit(:name, project_criteria: [:name, :type, :benefit] )
Your case is somewhat compounded by the fact that you're dealing with multiple nested objects, so you'll have to pass a hash instead:
params.require(:project).permit(:name, { project_criteria: [:name, :type, :benefit]} )