为什么你必须使用fetch for Rails参数?

时间:2017-06-05 18:39:13

标签: ruby-on-rails parameters

docs中,他们有:

params = ActionController::Parameters.new(person: { name: "Francesco" })

然后使用params.fetch(:person)来吸引人,但你不能params[:person]吗?得到相同的数据?

2 个答案:

答案 0 :(得分:5)

我认为这取决于你想要的行为。

params = ActionController::Parameters.new
params.fetch(:person)

会引发错误。如文档所示,如果您愿意,可以使用fetch指定进一步的行为。

params = ActionController::Parameters.new
params[:person]

将返回nil

答案 1 :(得分:3)

  

为什么你必须使用fetch for Rails参数?

你没有。

您正在查看documentation for fetch method。当然,它到处使用fetch。还有[] method

params = ActionController::Parameters.new(person: { name: "Francesco" })
params[:person] # => <ActionController::Parameters {"name"=>"Francesco"} permitted: false>
params[:none]   # => nil
相关问题