Home > database >  Permit array of strong params without using nested attributes
Permit array of strong params without using nested attributes

Time:10-21

I have an array of users I want to save in my database. An example when shown in the console after a POST is made:

"users"=>[{"name"=>"Job", "email"=>"*****"}, {"name"=>"Ed", "email"=>"****"}]

No nested attributes going on here. How to format strong params for this?


def user_params
  params.fetch(:user, {}).permit(:name, :email, ...)
end

This may work for saving a single user but I'm passing an array of users. I'm currently storing the user in a "dirty" manner:


users = params[:users]

users.each do |user|
  User.create(name: user[:name], email: user[:email])
end

I'd like to refactor and do something like:

User.create(user_params)

CodePudding user response:

To permit a param key containing an array of hashes you pass the name as the key and an array of permitted attributes:

def user_params
  params.permit(users: [:name, :email, ...])
        .fetch(:users, [])
end

The output will be an array of ActionController::Parameters instances or an empty array if the key is not present:

[#<ActionController::Parameters {"name"=>"Job", "email"=>"*****"} permitted: true>,
 #<ActionController::Parameters {"name"=>"Ed", "email"=>"****"} permitted: true>]
  • Related