How to do strong parameters with an array of objects
Asked Answered
R

1

6

If I have a user

def user_params
    params.require(:user).permit(:name, :age)
end

I got that down. I want to batch create users. So a user can fill out a list (theoretically endless) of users, they would come in as:

[{name: "name", age: 12},{name: "name", age: 22},{name: "name", age: 32}]

Question is, how do I use strong parameters for that? I know that I can just loop through the array and create the records, I get that. My understanding is that strong params are a generally good idea, safety wise.

What are strong params protecting me from? What would I be opening myself up to here, if I just looped over the array of users? How can I do it properly, either with strong params, or an alternate method?

Ramsay answered 25/10, 2016 at 2:1 Comment(0)
O
6

The entire point of strong parameters (introduce in rails 4) with the goal of protecting applications from mass assignment vulnerabilities. Like for example, lets say you had a User model and it had a admin attribute. If you were using mass assignment in theory someone could slip in a value for the admin attribute if you did not filter it out some how; see below

class UserController < ApplicationController

  def create
    #{name: 'Joe', score: 7, title: 'Mr', admin: true} params hash
    User.create(params)
  end
end

Now if some how a user of your app passed in these values they just made themselves and admin and can do as they please. So thats why you would use strong params to do this.

class UserController < ApplicationController

  def create
    User.create(user_params)
  end

  def user_params
    params.require(:name).permit(:title, :score)  #noticed admin is not allowed
  end
end

Now to create multiple records with strong params you could do this

class UserController < ApplicationController

  def create
    user_params[:users].each do |u|
      User.create(u)
    end
  end

  def user_params
    params.permit(:users, array: [:name, :age])
  end
end
Ointment answered 25/10, 2016 at 2:12 Comment(3)
This doesnt work. NoMethodError (undefined method `permit' for #<Array:0x007fbe1b9ad770> Did you mean? print):Ramsay
Updated the answerOintment
I was struggling with the same, and I think the right answer is to use params.permit(:users => [:name, :age]). Just a FYI for anyone else that happens upon this answer.Souffle

© 2022 - 2024 — McMap. All rights reserved.