简体   繁体   English

多个键在rails中的strong_parameters

[英]strong_parameters in rails for multiple keys

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. 现在,我想使用强大的参数来过滤掉这些键。 ie

#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: 更新2:这是正确的答案:

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

Thanks @R_O_R and @twonegatives helping me out and bearing with me :) 谢谢@R_O_R和@twonegatives帮助我,并与我保持联系:)

Well you want 好吧,你想要

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

Nested Parameters 嵌套参数

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 引用Rails 4强参数嵌套对象

UPDATE 更新

As of your question about slice , well, that usage is possible aswell. 至于您对slice的问题,那么这种用法也是可以的。 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. 简而言之,早在2012年,人们就使用了Rails 3,它没有提供任何过滤控制器中传入参数的方法,因此使用了slice方法。 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). 关于这个时间的一些参考甚至可以在stackoverflow上找到(请参阅大规模分配切片 )和在github上找到(这里是Ruby on Rails的创建者DHH的要旨 )。 At the end of the day, strong parameters gem is simply an extraction of the slice pattern. 归根结底, strong parameters gem只是slice模式的提取。 But for now it would be more convenient to follow permit pattern for Rails 4. 但是现在,遵循Rails 4的permit模式会更加方便。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM