Search code examples
ruby-on-railsacts-as-commentable

acts_as_commentable examples?


I have a model that I want to be commentable. I am having difficulty creating a form on my model's 'show' view that will allow comments to be created. I am not finding any good or useful examples. Can anyone point me to or show me an example of how to do this?

Example:

A simple blog application. I have a model called Post. It is commentable. So on the 'show' view I want to show a Post and, at the bottom, have the fields that, when completed and submitted, create a new comment associated with the post and put it in the database.

Sounds straightforward and I have it working so I can display comments that I have seeded. I just can't get a form to work to put new ones in. Any help is appreciated.


Solution

  • This is very, very basic stuff and you clearly need some better structure and approach to your learning. Buying a book, such as Agile Web Development with Rails, is the only real way to learn, otherwise you'll wander from problem to problem without ever actually learning anything well.

    Say you have a post that you want to comment.

    #routes.rb
    map.resources :posts do |post|
      post.resources :comments
    end
    
    #post_controller.rb
    def show
      @post.find params[:id]
      @comment = @post.comments.new
    end
    
    #posts/show.html.erb
    <%- form_for [@post, @comment] do |f|-%>
      <%= f.text_area :body -%>
      <%= f.submit -%>
    <%- end -%>
    
    #comments_controller
    def create
      @post = @post.find params[:post_id]
      @comment = @post.comments.new params[:comment]
      if @comment.save
        redirect_to @post