[英]How to add params id in rails link_to
I have a Job model that contains a Company_id as a foreign key. 我有一个包含Company_id作为外键的Job模型。 On the company show page, I want to use a link_to tag that links to the Job new page so I can create a new job with the company_id using simple_form.
在公司展示页面上,我想使用链接到Job新页面的link_to标记,以便可以使用simple_form使用company_id创建新工作。
<%= link_to "Create Job", new_company_job_path %>
I get this error "No route matches {:action=>"new", :controller=>"jobs", :id=>"13"}, missing required keys: [:company_id]" This is my nested route 我收到此错误“没有路由匹配{:action =>“ new”,:controller =>“ jobs”,:id =>“ 13”},缺少必需的键:[:company_id]“这是我的嵌套路由
resources :companies do
resources :jobs, only: [:new, :create, :update, :destroy]
end
From rails routes, this is the route to the job new page 从铁路路线,这是到工作新页面的路线
new_company_job GET /companies/:company_id/jobs/new(.:format) jobs#new
This is the simple-form in the job_new page 这是job_new页面中的简单形式
<%= simple_form_for (@job) do |f| %> etc
I would like know how I can include the company_id in to the link_to tag in order to use simple_form in the job new_page to create a new job. 我想知道如何将company_id包含在link_to标记中,以便在作业new_page中使用simple_form来创建新作业。
Rails routes can take arguments; Rails路由可以接受参数; if you ever want to explicitly pass a parameter to a route you can do so just like you would pass an argument to any other method:
如果您想显式地将参数传递给路由,则可以像将参数传递给任何其他方法一样进行操作:
<%= link_to "Create Job", new_company_job_path(company_id: @company.id) %>
*note: this assumes you have defined @company
somewhere on this view. *注意:这假设您在此视图的某处定义了
@company
。
In the case of general resource routes, Rails is smart enough to insert these params in the right place. 对于一般资源路线,Rails足够聪明,可以将这些参数插入正确的位置。 It's worth noting though that if a param is not defined on the route in routes.rb Rails will tack on these passed parameters to the end of the route as query strings.
值得注意的是,如果在route.rb中的路由上未定义参数,Rails会将这些传递的参数作为查询字符串添加到路由的末尾。
For example, if you have a route like 例如,如果您有一条类似
get 'landing_pages/page' => '#landing_pages#page'
and you called: 然后您致电:
<%= link_to "Go to your landing page", landing_pages_page_path(brand: 'Apple') %>
The route will become /landing_page/page?brand=Apple
该路线将变为
/landing_page/page?brand=Apple
For further reference: http://guides.rubyonrails.org/routing.html 有关更多参考: http : //guides.rubyonrails.org/routing.html
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.