简体   繁体   English

如何在Rails中正确定义获取和发布路线?

[英]How to correctly define the get and post routes in rails?

Recently I've been working with rails. 最近,我一直在使用Rails。 I have a form with form_tag, which receives a helper post from routes.rb. 我有一个带有form_tag的表单,该表单接收来自route.rb的帮助帖子。 I have the same route in get to access this form, and I have the route in posrt to be able to send the data of the previous form: 我在访问此表单时有相同的路由,在posrt中有路由,可以发送前一个表单的数据:

get 'students/:student_id/monitorings/inscribir', to: 'monitorings#inscribir', as: :inscribir_student_monitoring
post 'students/:student_id/monitorings/inscribir', to: 'monitorings#inscribir', as: :inscribir_student_monitoring_post

My question is, how can I separate these routes? 我的问题是,如何分隔这些路线? Since, according to investigating, this can cause problems, since both have the same address, and really if it is causing me problems, since when entering this link the form is executed automatically. 因为根据调查,这可能会引起问题,因为两者都有相同的地址,并且如果确实引起了我的麻烦,那么在输入此链接时会自动执行表格。

Do you necessarily have to separate the two routes? 您是否必须将两条路线分开? And if that is true, how can I do it? 如果那是真的,我该怎么办? I tried something similar to what rails do with respect to the method get new and post create method but adapted to my case, but it has not worked for me. 我尝试过类似rails的方法,使方法get new和post create方法适应我的情况,但对我来说不起作用。

Thank you. 谢谢。

Do you necessarily have to separate the two routes? 您是否必须将两条路线分开?

No! 没有! Unless your both routes have a same name , it won't be a problem. 除非您的两个路线都具有相同的名称 ,否则不会有问题。 For instance if you have routes like below 例如,如果您有以下路线

get 'students/:student_id/monitorings/inscribir', to: 'monitorings#inscribir', as: :inscribir_student_monitoring
post 'students/:student_id/monitorings/inscribir', to: 'monitorings#inscribir', as: :inscribir_student_monitoring

then Rails would rails an exception like so 然后Rails会像这样一个异常

ArgumentError: Invalid route name, already in use: 'inscribir_student_monitoring' You may have defined two routes with the same name using the :as option, or you may be overriding a route already defined by a resource with the same naming. ArgumentError:无效的路由名称,已经在使用:'inscribir_student_monitoring'您可能使用:as选项定义了两个具有相同名称的路由,或者您可能使用相同的命名覆盖了已经由资源定义的路由。 For the latter, you can restrict the routes created with resources as explained here: http://guides.rubyonrails.org/routing.html#restricting-the-routes-created 对于后者,您可以按照以下说明限制使用resources创建的路由: http : //guides.rubyonrails.org/routing.html#restricting-the-routes-created

Since your routes have a different name , this won't be a worry. 由于您的路线名称不同 ,因此不必担心。 Though you can shorten your code by using match 虽然您可以使用match来缩短代码

match 'students/:student_id/monitorings/inscribir', to: 'monitorings#inscribir', via: [:get, :post]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM