Pra*_*tha 4 ruby hash ruby-on-rails
我想获得任何额外的GET和POST PARAMS Rails中没有Rails的自己的添加,如controller,format等...
params.inspect给了我我想要的东西,但它有一些 Rails 为我添加的键,例如controller或format。我只想获取用户输入GET和POST参数作为哈希值。我怎样才能做到这一点?我找不到任何东西。
网址:
http:/test.com/some/path?query1=1&query2=1
跑:
puts params.inspect
预期的:
{"query1"=>"1", "query2"=>"1"}
实际的:
{"query1"=>"1", "query2"=>"1", "format"=>":json", "controller"=>"get", "action"=>"index", "folder"=>"some/path"}
这也可以与 POST 请求结合使用。我只想过滤它们并且只将它们作为哈希值。
我从控制器内部执行此操作。使用导轨 5。
您应该允许使用参数(强参数)。
在您的控制器中允许使用 params 方法。
def your_params
params.permit(:query1, :query2)
end
Run Code Online (Sandbox Code Playgroud)
如果你想有一个散列,你可以做
your_params.to_h #This will return hash of permitted params
Run Code Online (Sandbox Code Playgroud)
更新:
如果您有多种query*类型的参数,您可以选择它们并允许!. 这是命令行解释
# passing the list of parameters
> params = ActionController::Parameters.new({query1: 'aa', query2: 'bb', query3: 'cc', controller: 'users', action: 'index'})
=> <ActionController::Parameters {"query1"=>"aa", "query2"=>"bb", "query3"=>"cc", "controller"=>"users", "action"=>"index"} permitted: false>
# Select all the parameters of type query<integer>
> all_queries = params.select {|i| i.match?(/query\d/) }
=> <ActionController::Parameters {"query1"=>"aa", "query2"=>"bb", "query3"=>"cc"} permitted: false>
# mark the selected as permitted
> all_queries.permit!
=> <ActionController::Parameters {"query1"=>"aa", "query2"=>"bb", "query3"=>"cc"} permitted: true>
# get them as hash
> all_queries.to_h
=> {"query1"=>"aa", "query2"=>"bb", "query3"=>"cc"}
Run Code Online (Sandbox Code Playgroud)
控制器方法看起来像
# getting all query<integer> like params
def your_params
params.select {|param| param.match?(/query\d/}.permit!
end
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
7008 次 |
| 最近记录: |