Say that I have two resources, Project and Task. A Project can have many Tasks; A Task belongs to one Project. Also say that I have Task nested under Project in routes.rb:
假设我有两个资源,Project和Task。一个项目可以有很多任务;任务属于一个项目。还要说我在routes.rb中的Project下嵌套了Task:
map.resources :projects do |project|
project.resources :tasks
end
Can one programmatically discover this relationship? Basically, I need to dynamically load an arbitrary object, then figure out if it has a "parent", and then load that parent.
可以通过编程方式发现这种关系吗?基本上,我需要动态加载任意对象,然后确定它是否有“父”,然后加载该父对象。
Any ideas?
2 个解决方案
#1
Routing will not help you as this is only meant to be used the other way around. What you can do is aliasing the relationship with :parent:
路由不会帮助你,因为这只是用于反过来。您可以做的是将关系别名化为:parent:
class Task
belongs_to :project
alias :project :parent
end
And then use this relationship to detect if a parent object is available:
然后使用此关系来检测父对象是否可用:
if object.respond_to?(:parent)
# do something
end
Moreover, you can use polymorphic routes if the routes are set up correctly:
此外,如果路由设置正确,您可以使用多态路由:
polymorphic_url([object.parent, object])
#2
Your code above determines the relationship for the routes and helps generate the right helpers to create paths and such.
上面的代码确定了路由的关系,并帮助生成正确的帮助程序来创建路径等。
What you need to make sure is that the relationships are properly declared in your madels. In the project model you should have:
您需要确保在您的婚姻中正确宣布关系。在项目模型中,您应该:
has_many :tasks
In your task model you should have:
在您的任务模型中,您应该:
belongs_to :project
Once you have set that up, you are ready to get what you want.
一旦你完成了设置,你就可以得到你想要的东西了。
@task = Task.first
unless @task.project.blank?
project_name = @task.project.name
end
#1
Routing will not help you as this is only meant to be used the other way around. What you can do is aliasing the relationship with :parent:
路由不会帮助你,因为这只是用于反过来。您可以做的是将关系别名化为:parent:
class Task
belongs_to :project
alias :project :parent
end
And then use this relationship to detect if a parent object is available:
然后使用此关系来检测父对象是否可用:
if object.respond_to?(:parent)
# do something
end
Moreover, you can use polymorphic routes if the routes are set up correctly:
此外,如果路由设置正确,您可以使用多态路由:
polymorphic_url([object.parent, object])
#2
Your code above determines the relationship for the routes and helps generate the right helpers to create paths and such.
上面的代码确定了路由的关系,并帮助生成正确的帮助程序来创建路径等。
What you need to make sure is that the relationships are properly declared in your madels. In the project model you should have:
您需要确保在您的婚姻中正确宣布关系。在项目模型中,您应该:
has_many :tasks
In your task model you should have:
在您的任务模型中,您应该:
belongs_to :project
Once you have set that up, you are ready to get what you want.
一旦你完成了设置,你就可以得到你想要的东西了。
@task = Task.first
unless @task.project.blank?
project_name = @task.project.name
end