[英]Rails Route for Adding child to parent
Been working in another language for a few months and trying to get back into Rails. 使用另一种语言工作了几个月,并尝试重新使用Rails。
If I have a model House
, and a model Door
, so that Door
belongs_to
House
and House
has_many Doors
. 如果我有一个样板
House
和一个样板Door
,那么该Door
belongs_to
House
,而样板House
Doors
。
If I want to add a door
to the house
, do I use the route: 如果我想给
house
加一door
,是否使用以下路线:
add_door_path
or is it 还是
add_door_path(@house)
And if so how do I embed the house_id
in to it? 如果是的话,如何将
house_id
嵌入其中? Or do I need to create a new route for that? 还是我需要为此创建一条新路线? Is it part of the standard
resources
or is this entirely custom? 它是标准
resources
一部分还是完全定制的?
if you have 如果你有
# routes.rb
resources :house do
resources :doors
end
then you would have house_doors_path(@house)
那么你会有
house_doors_path(@house)
That is because in your routes you have specified that doors is nested inside the house. 这是因为在您的路线中,您已指定门嵌套在房屋内。 You would need the parameter inside because the path requires a house id.
您需要内部的参数,因为路径需要房屋ID。
To check for the routes, go here http://localhost:3000/rails/info/routes
. 要检查路线,请访问
http://localhost:3000/rails/info/routes
。
If on the other hand, if you have 另一方面,如果您有
# routes.rb
post '/door/' => 'doors#create', as: :add_door
the new door would not know which house it belongs to. 新门将不知道它属于哪个房子。 so you can add
post '/house/:id/door ...
which you also need a parameter of house so your syntax would be add_door_path(@house)
因此,您可以添加
post '/house/:id/door ...
,并且还需要一个house参数,因此语法为add_door_path(@house)
I hope that answers your question. 我希望能回答您的问题。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.