作者:林小秋 | 来源:互联网 | 2023-06-06 21:17
Igeneratedanewrails5--api--databasepostgresqlapptheotherdayandonlycreatedonescaffol
I generated a new rails 5 --api --database=postgresql app the other day and only created one scaffold (Hero). I'm wondering how the strong parameters work in rails as I am seeing some odd behavior:
我前几天生成了一个新的rails 5 --api --database = postgresql app,只创建了一个脚手架(Hero)。我想知道强大的参数如何在rails中工作,因为我看到一些奇怪的行为:
Controller looks like:
控制器看起来像:
def create
hero = Hero.new(hero_params)
if hero.save
render json: hero, status: :created, location: hero
else
render json: hero.errors, status: :unprocessable_entity
end
end
My hero_params look like this:
我的hero_params看起来像这样:
def hero_params
params.require(:hero).permit(:name)
end
So I would assume that the client is required to submit a hash containing a "hero"
key and it's allowed to have a "name
" subkey that is allowed to be mass assigned when this controller action is called.
所以我假设客户端需要提交一个包含“英雄”键的哈希值,并允许它有一个“名称”子键,当调用此控制器操作时,该子键可以被批量分配。
Meaning, the JSON should look like this:
意思是,JSON应该如下所示:
{
"hero": {
"name": "test"
}
}
All is well but here is where I am seeing strange behavior. When the user submits the exact JSON as above, the parameters come in as:
一切都很好,但这里是我看到奇怪的行为。当用户提交上面的确切JSON时,参数如下:
Parameters: {"hero"=>{"name"=>"test"}}
Now if the user submits just:
现在,如果用户只提交:
{ "name": "test" }
It still creates a new resource and the parameters come in as:
它仍然创建一个新资源,参数如下:
Parameters: {"name"=>"test", "hero"=>{"name"=>"test"}}
Why are there two sets of parameters, one with the actual submitted data and one in the format of a hero object as if it was anticipating the mass assignment?
为什么有两组参数,一组是实际提交的数据,另一组是英雄对象的格式,就好像它预期了质量分配一样?
How come the require(:hero)
doesn't raise an error when that key is not submitted? I assume the answer to this is because of what is automatically creating that second hash ("hero"=>{"name"=>"test"}}
from question 1.
为什么在未提交该密钥时,require(:hero)如何不引发错误?我假设答案是因为从问题1中自动创建第二个哈希(“hero”=> {“name”=>“test”}}。
Any information on what I am missing here would be greatly appreciated, as this is barebones rails behavior out-of-the-box.
任何有关我在这里缺少的信息都将非常感激,因为这是开箱即用的准系统导轨行为。
1 个解决方案