我是 Ruby on Rails 的新手,在一个项目中使用 4.1 版。
我对嵌套资源在 Rails 中的工作方式有点困惑。也许有人可以提供帮助。
我正在构建一个任务分配系统作为一个学习项目。
我的网站有属于他们的任务。查看任务时,我可以:
resources :websites do
resources :tasks
end
一个链接会把我带到我的任务就好了,像http://myapp.com/websites/2/tasks/3这样的网址
<%= link_to 'Show', website_task_path(website,task) %>
不过我注意到,我可以将网址中的网站 ID 更改为任何内容 - http://myapp.com/websites/what-the-hell-is-going-on-here/tasks/1 - 与其他链接的工作方式相同。或者我也可以在 url 中使用不同的网站 ID 访问该任务。
所以问题是,默认情况下,Rails 是否应该对这条信息做任何事情?我是否想确保您使用参数中的正确父资源访问任务取决于我吗?
最佳答案
您的任务 ID 在任务表中是唯一的。只要您想显示、编辑或删除任务,这些信息就足够了。你可以很容易地通过你的协会得到 parent 。但是嵌套资源允许您创建新任务。在这种情况下,没有设置 ID。您需要知道正确的父级才能将其设置为您的任务。
摘自可能的 TasksController:
class TasksController < ApplicationController
before_action :set_website, only: [:create]
def create
@website.tasks.create!(task_params)
end
private
def set_website
@website = Website.find(params[:website_id])
end
def task_params
params.require(:task).permit(:title, :text)
end
end
生成的嵌套路由:
# Routes without :task_id - Parent matters!
website_tasks
GET /websites/:website_id/tasks(.:format) tasks#index
POST /websites/:website_id/tasks(.:format) tasks#create
new_website_task
GET /websites/:website_id/tasks/new(.:format) tasks#new
# Routes with :task_id - Parent redundant.
edit_website_task
GET /websites/:website_id/tasks/:id/edit(.:format) tasks#edit
website_task
GET /websites/:website_id/tasks/:id(.:format) tasks#show
PATCH /websites/:website_id/tasks/:id(.:format) tasks#update
PUT /websites/:website_id/tasks/:id(.:format) tasks#update
DELETE /websites/:website_id/tasks/:id(.:format) tasks#destroy
您可以使用浅层嵌套从冗余的 website_id 中清除路由。这个有详细解释in the Rails docs .
基本意思是:
resources :website do
resources :tasks, only: [:index, :new, :create]
end
resources :tasks, only: [:show, :edit, :update, :destroy]
这与写作相同:
resources :websites do
resources :tasks, shallow: true
end
可能有一些完整路径很有值(value)的用例,例如。 G。您希望将其提供给搜索引擎,或者您希望 URL 对读者更有说服力。
关于ruby-on-rails - Rails 嵌套资源参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29571840/