In my rails app, movie/book and post are in the polymorphic relationship. In
posts/show.html.erb, I tried to add ‘Edit’ and ‘Delete’ function. The problem was how to write related path.
At first, I used if…else condition to judge @postable_type. When it equals to ‘Book’, then showed
edit_book_post_path(@post.postable_id, @post) and
book_path(@post.postable_id), and if it equals to ‘Movie’, then showed the related movie path.
It worked fine, but a little bit complicated. The same problem when I render the comments partial, I had to use two different files to handle edit/delete comment path.
Then I found polymorphic_path method on RailsGuides and some articles on the Web.
Briefly speaking, the final code I use like this:
Now, I can abandon the if…else condition and use the same template whatever the @postable is.
I also refactor the controller like this:
Doing this way, it’s simple and clear.