Polymorphic Routes in Rails
In Rails, you can define a model as polymorphic like the following:
class Post
has_many :comments, as: :commentable
end
class NewsItem
has_many :comments, as: :commentable
end
class Comment
belongs_to :commentable, polymorphic: true
end
And I believe your resources would look like this:
resources :posts
resources :comments
end
resources :news_items
resources :comments
end
And you can view all comments in a post through the link: /posts/1/comments
(the path helper would be post_comments_path
). The link to view all comments in a news_item would be very similar: news_items/1/comments
(helper: news_item_comments_path
).
However, Rails is intelligent enough to know that you have polymorphic association in your model and it can generate corresponding link based on the model you pass in. You can use helper polymorphic_path
(or polymorphic_url
) to get the correct link.
For example:
polymorphic_path(@post, Comment) # => posts/1/comments
polymorphic_path(@news_item, Comment) #=> news_items/1/comments
And in the controller of nested resources, you can check for the presence of params[:post_id]
or params[:news_item_id]
to know parent item you are referring to
class CommentsController < ApplicationController
def create
if params[:post_id]
parent = Post.find(params[:post_id])
else if params[:news_item_id]
parent = NewsItem.find(params[:news_item_id])
end
comment = Comment.new
comment.commentable = parent
...
end
end
Hope this helps you refactor your code to make it look better.