Question

Question

In a polymorphic model, thats used in nested controllers, how can I abstract my delete link's path so I'm not hardcoding upload_permitted_user_path(@permissible, permitted_user)?

Details

I have a polymorphic model called permitted users. Basically theres a bunch of objects in my application where we need to control who can see it. So a post, photo, etc can have permitted users.

I want to be able to delete permitted users on the post#edit, photo#edit, etc pages.

I have this line:

# Used in "posts#edit"
<%= link_to 'Delete', 
  post_permitted_user_path(@permissible, permitted_user), # This should not be hardcoded.
  method: :delete, 
  data: { confirm: 'Are you sure?' } %>

# Used in "photos#edit"
<%= link_to 'Delete', 
  photo_permitted_user_path(@permissible, permitted_user), # This should not be hardcoded.
  method: :delete, 
  data: { confirm: 'Are you sure?' } %>

How can I abstract the path so I'm not hardcoding <MY_TOP_LEVEL_CLASS>_permitted_user_path(@permissible, permitted_user)?

Was it helpful?

Solution

Found the answer (feel free to repost and I'll accept :P)

Creating polymorphic links is easy using "polymorphic routes".

You can easily generate the proper link using polymorphic_url([@top_resource, @next_level_resource]) in any view.

For example:

polymorphic_url([:admin, @article, @comment]) becomes admin_article_comment_url(@article, @comment).

Another example without the leading :admin:

polymorphic_url([@article, @comment]) becomes article_comment_url(@article, @comment).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top