I have a problem related to polymorphic associations.
Currently in my routes i define the following:
map.resources :articles do |articles|
articles.resources :comments
end
map.resources :posts do |posts|
posts.resources :comments
end
I have basically posts and articles models which relate to the
polymorphic model comment.
Routes are generated as I expect to, but the problem resides in the
comments_controller, since in this controller I'm not able to figure out
if I'm creating a comment for a post or for an article.
def determine_parent
@parent = Article.find_by_id(params[:article_id]) ||
Post.find(params[:post_id]
end
def ensure_valid_comment
return unless params[:id]
raise ActiveRecord::RecordNotFound unless
@parent.comments.find(params[:id])
end
end
This will first look for an article, and if that fails (returns nil),
it will assume it's a post. Raises an exception of neither are
found. The second filter helps ensure that someone didn't mess with
the url.