如何在Rails中获取GET和POST参数作为哈希?

时间:2017-10-31 13:42:32

标签: ruby-on-rails ruby hash

我想在没有Rails的Rails中获得任何额外的GETPOST 参数。自己的附加内容,例如controllerformat等......

params.inspect给了我想要的内容,但它有一些Rails为我添加的密钥,例如controllerformat。我只想将用户输入GETPOST参数作为哈希。我怎样才能做到这一点?我找不到任何东西。

URL:

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请求结合使用。我只想过滤它们,只将它们作为哈希值。

我从控制器内部执行此操作。使用Rails 5。

2 个答案:

答案 0 :(得分:4)

  

您应该允许参数(Strong parameters)。

在你的控制器中允许使用params方法。

def your_params
  params.permit(:query1, :query2)
end

如果你希望得到那些你可以做的哈希

your_params.to_h #This will return hash of permitted params

更新

如果您有多个query*类型的参数,可以selectpermit!。这是命令行说明

# 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"}

控制器方法看起来像

# getting all query<integer> like params
def your_params
  params.select {|param| param.match?(/query\d/}.permit!
end

答案 1 :(得分:1)

在控制器中,您可以访问request对象。 request有一个方法query_parameters,它将返回仅显式提供的参数的哈希值。

`request.query_parameters`

http://api.rubyonrails.org/classes/ActionDispatch/Request.html#method-i-query_parameters