Generate polymorphic URL in Rails
Contact me at LinkedIn  RailsZilla at Facebook  RailsZilla at twitter   google +1  Contact me at Xing  connect me at github

Generate polymorphic URL in Rails

Posted in Rails

In this example, I want to explain a best practice for Polymorphic URLs in Rails. I will show really bad things here as an illustrative example.
Don’t worry, we will refactor the code later ;-)

Let us assume that we have three models, Post, News and Comment. In most cases, a post has many comments and a news has many comments. They are defined like:

1
2
3
4
5
6
7
8
9
class Post < ActiveRecord::Base
  has_many :comments
end
class News < ActiveRecord::Base
  has_many :comments
end
class Comment < ActiveRecord::Base
  belongs_to :commentable, :polymorphic => true
end

Now we open our routes.rb file and we define the routes like:

1
2
3
4
5
6
resources :posts do
  resources :comments
end
resources :news do
  resources :comments
end

How are you mostly generate the url for posts’ comments and news’ comments? Many people write this to get the url for post-comments and news-comments:

Bad example …

1
2
3
4
5
6
# parent may be a post or a news
if Post === parent
  post_comments_path(parent)
elsif News === parent
  news_comments_path(parent)
end

This could get the URL for post and news:

1
2
3
4
5
if Post === parent
  post_path(parent)
elsif News === parent
  news_path(parent)
end

Let’s Refactor the code
Rails provides a simple way to generate the polymorphic url.
So we can use the polymorphic_path to get the url for post comments and news comments.

1
2
#"/posts/1/comments" or "'news/1/comments"
polymorphic_path([parent, Comment])

To get the url for post and news

1
2
#"http://example.com/posts/1/comments" or #"http://example.com/news/1/comments"
polymorphic_path(parent)

Lession learned:
polymorphic_path makes polymorphic url generation much easier and simpler. There is also a method named polymorphic_url which is the same as the polymorphic_path, except that polymorphic_url generate the full url including the host name.

Besides these, rails also provides the new and edit action for polymorphic_path/polymorphic_url

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
###
# we do a rake routes in our console
###

# "/posts/new"
new_polymorphic_url(Post)

# "http://example.com/posts/new"
new_polymorphic_path(Post)        

# "/posts/1/edit"
edit_polymorphic_path(post)    

# "http://example.com/posts/1/edit"
edit_polymorphic_url(post)

Tags: , , ,

Leave a Reply

Your email address will not be published. Required fields are marked *

Please enter a secure code to see if you are a spammer ;-)

 

Copyright © 2011-2017  - RailsZilla – Ruby on Rails tutorials, tips and tricks All rights reserved. | Imprint | Privacy