I am using polymorphic association.
I have 2 models articles and events which have has_many association with comments model using polymorphic association
Inside comments controller :
def index
@commentable = find_commentable
@comments = @commentable.comments
end
def find_commentable
params.each do |name, value|
if name =~ /(.+)_id$/
return $1.classify.constantize.find(value)
end
end
nil
end
Inside article and event model i wrote:
has_many :comments, :as => :commentable,:dependent => :destroy
Inside comments model:
belongs_to :commentable, :polymorphic => true
Inside routes :
resources :articles do
resources :comments
end
my problem is
1) When I enter http://localhost:3003/articles/8/comments it gives the following error:
undefined method `comments' for nil:NilClass
2) Also I dont want to use nested routes, I want to use simple routes. How can I achieve the same thing as this code is doing?
You’re receiving this error because @commentable is nil. Do you have an article with an ID of 8? Is find_commentable function is returning the commentable correctly? My guess is the answer to one of those two questions is “no.”
If you don’t want nested routes, you can just do
resources :commentsbut you should be sure you pass in commentable_type and commentable_id as params to the controller; otherwise you won’t be able to look up the commentable class to get its comments.