Reputation: 260
I have a controller/model called contacts
and I have 2 other models that have a many to many relationship with contacts, ie: users
and franchises
. I have been playing with nested routes and I can make /users/1/contacts work fine but what if I wanted to do /franchises/1/contacts? Is there a dynamic way to solve this? or would I need to do
if FRANCHISE
<%= link_to "Edit", edit_franchise_contact_path(@contact) %>
elsif USER
<%= link_to "Edit", edit_user_contact_path(@contact) %>
end
The only other method I can see is making a method in the respective controller that can deal with managing contacts. I appreciate the help.
Upvotes: 1
Views: 966
Reputation: 3689
What about polymorphic urls?
polymorphic_url(record_or_hash_or_array, options = {})
Constructs a call to a named RESTful route for the given record and returns the resulting URL string. For example:
# calls post_url(post)
polymorphic_url(post) # => "http://example.com/posts/1"
polymorphic_url([blog, post]) # => "http://example.com/blogs/1/posts/1"
polymorphic_url([:admin, blog, post]) # => "http://example.com/admin/blogs/1/posts/1"
polymorphic_url([user, :blog, post]) # => "http://example.com/users/1/blog/posts/1"
polymorphic_url(Comment) # => "http://example.com/comments"
In your case: polymorphic_url([@franchise_or_user, @contact], :action => :edit)
Or simply: edit_polymorphic_url([@franchise_or_user, @contact])
See: http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html
Upvotes: 1