在嵌套关联中使用多态路径 [英] Using polymorphic paths with nested associations

查看:62
本文介绍了在嵌套关联中使用多态路径的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个看起来像这样的多态关联:

I have a polymorphic association that looks like this:

class Line < ActiveRecord::Base
   belongs_to :item, :polymorphic => true
end

class Education < ActiveRecord::base
   has_many :lines, :as => :item
end

class Work < ActiveRecord::base
   has_many :lines, :as => :item
end

我想要一种从父项创建新行的简单方法.因此,我可能正在编辑Work对象的视图,并希望有一个创建新Line对象的链接.通常,我会这样做:

I'd like a simple way to create a new Line from the parent Item. So, I might be editing a view for a Work object, and want to have a link that creates a new Line object. Normally, I would do this:

<%= link_to "New Line", new_work_line_path(@work) %>

然后助手将为此工作.但是,这要求我检查Line在控制器中属于哪个父级,从而破坏了多态性的目的(如果是这种情况,我可以使用两个引用).因此,我的问题是,如何获得像正常路径助手一样多态工作的路径?

And the helper would work the route for this. However, this requires that I check which parent the Line belongs to in the controller, defeating the purpose of polymorphism (I could have used two references if that were the case). So, my question is, how do I get the path to work polymorphically like a normal path helper?

推荐答案

一种可能的方法是使用这样的路由:

A possible way could be to use routes like this:

map.resources :works do |works|
  works.resources :lines
end

map.resources :educations do |edu|
  edu.resources :lines
end

您的LinesController保持不变,您将获得以下路线:

Your LinesController remains the same, and you'll get routes like these:

work_lines GET    /works/:work_id/lines
....
education_lines GET    /educations/:education_id/lines
...

最烦人的部分是管理传递的第一个id,因为您将有params[:id]引用到Line,但是您还将有params[:work_id]params[:education_id].在这里,您必须选择检查传递的参数,还是至少解析请求的URL以确定您所在的位置(工作,教育等).

The most annoying part is to manage the first id passed, because you'll have a params[:id] referred to a Line, but you'll also have params[:work_id] or params[:education_id]. Here you must choose between checking which param is passed, or at least parse the requested url to determine in which you are (Works, Educations, etc...).

希望这有帮助;)

根据注释中出现的内容,可以使用polymorphic_url/polymorphic_path(

According to what emerged in comments, you can use polymorphic_url/polymorphic_path (http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html):

以这种方式使用它们很有意义:

It makes sense if you use them like this way:

link_to "New Line", polymorphic_url(@line.item,@line)
# => /<educations_or_works>/item_id/lines/line_id

至少,您甚至可以将其用于收藏集:

At least, you can even use it for collections:

link_to "New Line", polymorphic_url(@line.item,Line.new)
# => /<educations_or_works>/item_id/lines/

干杯,

这篇关于在嵌套关联中使用多态路径的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆