How do I set up the proper routes for an acts_as_commentable form?

86 Views Asked by At

There are two models: User, who does the commenting (provided by Devise), and Audio, which they comment on. Each audios#show page should list all comments for that audio, and have a little form through which to submit another one.

I made Audio acts_as_commentable. Then I made sure Comment belongs_to :user, and User has_many :comments.

For the routes, I have

resources :audios do 
  resources :comments
end

Then, on the audios_controller,

def show
  if user_signed_in?
    @comment = @audio.comments.new
  end
end

Then I wrote a simple form_for(@comment) form with a 'comment' field and a submit button. That's it.

The error I get upon loading the page is undefined method 'comments_path'. I googled this error, read the StackOverflow responses, and tried form_for(@audio, @comment) instead. This gets the error **can't write unknown attribute 'html'`.

I'm a little stumped; I've got the models and relationships sketched out on my notepad but I'm inexperienced and the use of things that I don't fully understand, like Devise behind the scenes, is throwing me for a loop. If someone could give me a tip on these routes/forms I would love it.

2

There are 2 best solutions below

0
Florin Ionita On

Try

form_for [@audio, @comment]

or

form_for @comment, url: audio_comment_path(@audio, @comment)
0
JuanBoca On

In routes.rb you need to have this:

# routes.rb
resources :comments, :only => [:create, :destroy]

The :comments route goes alone, outside from the resource you are trying to add the comment ability.

Then, if you run rake routes it will return:

$ rake routes
comments    POST        /comments(.:format)     comments#create
comment     DELETE  /comments/:id(.:format)     comments#destroy

This will give you the comments_path helper and comment_path(:id) helper to complete your POST and DELETE requests.

Check this tutorial, it helped me a lot when I needed to use this gem: http://twocentstudios.com/blog/2012/11/15/simple-ajax-comments-with-rails/