Comments on Acts As Commentable

I have received a bit positive feeback rearding the acts_as_commentable rails plugin. One suggestion asked for me to provide more sample code, especially in regards to the view and controller. To fulfill that request lets imagine that we are developing an application where different type of models act as commentable. We can start by creating a _comment_form.rhtml partial view that can be used by other views. The comment form should have the following fields:

<% start_form_tag :action => 'add_comment' %>
  <%= text_field 'comment', 'title' %>
  <%= text_field 'comment', 'comment' %>

  <%= submit_tag 'Add Comment' %>

  <%= hidden_field 'commentable', 'commentable', :value => @model.type %>
  <%= hidden_field 'commentable', 'commentable_id', :value => @model.id %>
<% end_form_tag %>

The @model variable holds an intance to the record you want to add a comment to. In this example, the add_comment action will be generic enough that it will be able to add comments to any ActiveRecord in the application. Because the add_comment action can add comments to say either Tasks or Posts you need to pass the model type to the action via a hidden field.

In the controller you can define the add_comment action like this:

def add_comment
  commentable_type = params[:commentable][:commentable]
  commentable_id = params[:commentable][:commentable_id]
  # Get the object that you want to comment
  commentable = Comment.find_commentable(commentable_type, commentable_id)

  # Create a comment with the user submitted content
  comment = Comment.new(params[:comment])
  # Assign this comment to the logged in user
  comment.user_id = session[:user].id

  # Add the comment
  commentable.comments << comment

  redirect_to :action => commentable_type.downcase,
    :id => commentable_id
end

In the sample code for the action there is an assumtion that only logged in user can add comments and that there is a action named after the commentable active record type.

Technorati Tags: , , , , ,