ruby-on-rails – Rails嵌套资源参数
我对
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 – 与其他链接的工作方式相同.或者我也可以在网址中使用不同的网站ID访问该任务. 所以问题是,Rails是否应该默认对这条信息做任何事情?如果我想确保您使用参数中的正确父资源访问任务,是否由我决定? 解决方法
您的任务ID在任务表中是唯一的.只要您想显示,编辑或删除任务,此信息就足够了.您可以通过您的关联轻松获得父母.但是嵌套资源允许您创建新任务.在这种情况下,没有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 可能存在一些完整路径有价值的用例,例如: G.您想将其提供给搜索引擎,或者您希望URL更适合读者. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
- 909422229_oracle转mysql 出现的问题已经解决思路
- arrays – 使用Swift中的值数组按属性过滤对象数
- ruby-on-rails – ActiveSupport :: Deprecation
- Ajax+Jsp+servlet+json技术的使用
- cocos2d_x_08_游戏_FlappyBird
- Flash 之ANE的applicationDeployment.nativeLibr
- c# – 如果未找到数据,SQL Server查询将连续返回
- 为什么这个正则表达式只在Python的行开头匹配?
- xml_to_array XML转成数组
- 从万象大会,看小程序如何满足搜索背后的海量潜在