Acts as commentable with threading how to setup create

395 Views Asked by At

Hi guys so apparently every newcomer knows and rages about the poor documentation that

acts_as_commentable_with_threading

provides - I'm no different.

I have a Post model, and I've made it

acts_as_commentable

as requested in the docs. Furthermore I've added the desired code in the show method for the post. Which are:

def show
 @post = Post.find(params[:id])
 @comments = @post.comment_threads.order('created_at desc')
 @new_comment = Comment.build_from(@post, current_user, "")
end

In the show I have:

<%= form_for @new_comment do |f| %>

  <%= f.label :body, 'Comment' %>
  <%= f.text_area :body %>

  <%= f.submit 'Post comment' %>

<% end %>

now obviously I realize I need to have a create action in the comments_controller. However I have no clue what to write in order to save the comment successfully. Any help?

1

There are 1 best solutions below

3
Maxim On

You should write something like this:

def create
    # Check structure of incomming parameters (use strong_params gem integrated with Rails)
    comment_params = params.requires[:comment].permit(:body)

    # Assign filtered parameters to new comment
    @comment = @post.comment_threads.build(comment_params)

    # Save it
    if @comment.save
        # If success then redirect to any page i.e. to your page with posts
        redirect_to { action: :index }, { notice: 'Your comment was saved!' }
    end

    # If not success then render form with error again
    render action: :show
end