Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to do strong parameters with an array of objects

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?

like image 979
Peter R Avatar asked Oct 25 '16 02:10

Peter R


1 Answers

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
like image 169
C dot StrifeVII Avatar answered Sep 21 '22 07:09

C dot StrifeVII