我有一个包含以下 ruby 代码的 View ,我想使用它在我的应用程序中创建动态链接:
<% @customer.jobs.each do |job| %>
<%= link_to job.id, job %>
<% end %>
这会为 job_path 抛出一个未定义的方法错误,这是有道理的,因为我的 jobs_controller show 方法是空的:
def show
end
这是我的路线:
resources :customers do
resources :jobs
end
我的问题是 - 如何在 Controller 中设置方法以使我的 link_to 在 View 页面上工作?
本质上,我是从数据库中提取一个项目,然后尝试使用该数据库项目创建指向相应 View 的链接。
有什么想法吗?
最佳答案
你有
<%= link_to job.id, job %>
此处第二个选项指定您的 url 或路径助手。 您收到此错误是因为您的路线没有 job_path 助手
要检查所有 url 或路径助手,请在您的终端中搜索路由。它会给你输出看起来像
Prefix Verb URI Pattern Controller#Action
customer_job GET /customers/:customer_id/jobs/:id(.:format) jobs#show
因此将您的链接替换为
<%= link_to job.id, customer_job_path(@customer,job) %>
更新:
引用您的评论:
@customer is an instance variable of your Customer model which you would have defined in your controller action(since you are using it in your view). Instance variables defined in your controller action are automatically available for its view. For details you should read docs
关于ruby-on-rails - Rails 动态 link_to 的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25169961/