strong_parameters in rails for multiple keys

855 Views Asked by At

I want to access three keys from params.

Say my params is:

params = {
   'product_id' =>  11,
   'category' => {
                   'name' => 'Pet',
                   'sub_categories' => {5 => 'Name1', 7 => 'Name2'} ## **UPDATE**
                   'id' => 100
    },
    'user_action' => 'save'
}

Now I want to use strong parameters to filter these key out. i.e

#Inside controller
#action
def save_product_category
  product_params[:product_id]
  product_params[:category]
  product_params[:user_action]
end

private
  def product_params
     params.permit(:product_id, :user_action, :category) # Doesn't work, eliminates 'category' key
  end

How do I filter out these three keys?

UPDATE: I found one way to do it:

params.slice(:product_id, :category, :user_action)

Is it right way to do it?

UPDATE 2: Here is the correct answer:

params.permit(:product_id, :user_action, :category => [:id, :name, :sub_categories => {}])

Thanks @R_O_R and @twonegatives helping me out and bearing with me :)

2

There are 2 best solutions below

6
On

Well you want

def product_params
  params.permit(:product_id, :user_action, category: [ :name, :id ])
end

Nested Parameters

5
On

You should explicitly define all the nested attributes of your parameters:

def product_params
  params.permit(:product_id, :user_action, category: [:id, :name] )
end

Reference to Rails 4 Strong parameters nested objects

UPDATE

As of your question about slice, well, that usage is possible aswell. Long story short, back in 2012 people used Rails 3 which did not provide any way of filtering incoming params in controller, so slice method was used for that purpose. Some references to that time can be even found here on stackoverflow (see slicing on mass assignment) and on github (here is a gist from DHH, creator of Ruby on Rails). At the end of the day, strong parameters gem is simply an extraction of the slice pattern. But for now it would be more convenient to follow permit pattern for Rails 4.