Reputation: 6324
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:
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?
Upvotes: 1
Views: 1608
Reputation: 2324
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:
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])
Upvotes: 1
Reputation: 9590
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
Upvotes: 0