【问题标题】:Rails nested resources routingRails 嵌套资源路由
【发布时间】:2013-11-11 00:23:28
【问题描述】:

我正在编写一个小型 Rub​​y-on-Rails 项目。我有 2 个模型:用户和任务

1 个任务属于两个用户(作者和目标用户),所以我在模型中做了:

    belongs_to :target, :class_name => 'User'
    belongs_to :author, :class_name => 'User'

当然,Users 模型有

    has_many :posts

所以,我希望能够通过 url/users/:username/tasks CRUD 用户的任务,而不是仅仅通过 /tasks 来完成它

所以我从 routes.rb 中删除了资源 :tasks 并添加了嵌套资源

    resources :users do
      resources :tasks
    end

我什至更新了视图(即 edit_task_path(task) 到 edit_user_task_path(task) )和 _form.html.erb 但我有一个错误:

Showing C:/Sites/todoit/app/views/tasks/index.html.erb where line #24 raised:
undefined method `task_path' for #<#<Class:0x458ce08>:0x458ad20>

我该怎么办?


帖子 index.html.erb:http://pastebin.com/DdGurSfe

【问题讨论】:

  • 你能发布app/views/tasks/index.html.erb 文件吗?
  • 当然。这里:pastebin.com/DdGurSfe
  • 由于tasks 是一个嵌套资源,您不会有task_path,而是类似user_task_path。在应用程序目录的控制台中运行 rake routes 应该可以让您了解可以使用的路径。

标签: ruby-on-rails ruby model-view-controller rails-routing


【解决方案1】:
<td><%= link_to 'Show', user_task_path(task) %></td>
# or
<td><%= link_to 'Show', [:user, task] %></td>

无论如何,请运行rake routes 以检查可用路线(除非您能够记住)。干杯!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-04-05
    • 2011-05-23
    • 1970-01-01
    • 2011-06-13
    • 1970-01-01
    • 1970-01-01
    • 2019-10-18
    • 2015-06-30
    相关资源
    最近更新 更多