Acts As Commentable Plugin

I am happy to announce that I have released the acts_as_commentable plugin, my first Ruby on Rails plugin. The Acts As Commentable plugin allows for comments to be added to your Rails ActiveRecord classes.

To install the Acts As Commentable plugin run the following command:

script/plugin install http://juixe.com/svn/acts_as_commentable

The installation process will add several ruby scripts in the vendor/plugins directory. Create a new rails migration and cut and past the following self.up and self.down methods:

def self.up
  create_table :comments, :force => true do |t|
    t.column :title, :string, :limit => 50, :default => ""
    t.column :comment, :string, :default => ""
    t.column :created_at, :datetime, :null => false
    t.column :commentable_id, :integer, :default => 0, :null => false
    t.column :commentable_type, :string, :limit => 15,
      :default => "", :null => false
    t.column :user_id, :integer, :default => 0, :null => false
  end

  add_index :comments, ["user_id"], :name => "fk_comments_user"
end

def self.down
  drop_table :comments
end

Once you have installed the plugin you can start using it in your ActiveRecord class simply by calling the acts_as_commentable method.

class Post < ActiveRecord::Base
  acts_as_commentable
end

To add a comment to a post object you can do the following:

comment = Comment.new(:title => titleStr, :comment => commentStr)
logger << "COMMENT #{comment.comment}\n"
post.comments << comment

Or you could have use the add_comment method on post.

post.add_comment comment

You can also use the post’s comments property to read all comments for the given post. Once a comment has been added to a post you can always reference the post object using the comment’s commentable property.

comment.commentable # references the post

One note, the default implementation of Acts As Commentable requires you to use a user model to link all comments to a user. This requirement can easily be removed or enhanced in the Comment class. But if you have a user model you can retrieve all comments for a user by executing the following statement:

comments = Comment.find_comments_by_user(userInstance)

If you want to retrieve only the comments for a user for a particular model you can do something like:

postComments = Post.find_comments_by_user(userInstance)

If you have any comments, questions, and/or suggestions please don’t hesitate to drop me a line.

Enjoy. Share. Be Happy.
  • Twitter
  • Facebook
  • StumbleUpon
  • del.icio.us
  • Tumblr
  • Google Bookmarks
  • FriendFeed
  • Yahoo! Buzz
  • Reddit
  • Digg
  • HackerNews
  • Suggest to Techmeme via Twitter
  • LinkedIn
  • Ping.fm
  • Identi.ca
  • Mixx
  • Furl

Related posts:

  1. Acts As Voteable Rails Plugin
  2. Comments on Acts As Commentable
  3. Acts As Bookmarkable Plugin
  4. Acts As Rateable Plugin
  5. Rails Plugin Tutorial

This entry was posted in Ruby, TechKnow. Bookmark the permalink. Post a comment or leave a trackback: Trackback URL.

34 Comments

  1. Posted January 29, 2007 at 3:28 pm | Permalink

    Just thought you might want to know: we’re using this on likebetter.com for photo commenting. thanks!

  2. Posted February 6, 2007 at 6:00 pm | Permalink

    I think something happened to this plugin with the newest version of rails. Basically, every time I reload the comment model it’s not picking up the belongs_to relationship. So:

    belongs_to :user

    Causes an ActiveRecord::AssociationTypeMismatch error. Says:

    User expected, got User

    That doesn’t make much sense. I know it’s probably a rails issue, but I thought you might have some insight. There are some other loading issues that are a bit too complex to explain in this little form.

  3. Posted February 7, 2007 at 2:05 am | Permalink

    @Bryan
    Did I see you give a presentation on likebetter at the January SV RoR meeting here in the Yay Area!? I was there! Thats a great application you have there…

    @famoseagle
    I think the issue that you are dealing with is that you don’t have a user model. The plugin comes with a comment model and this requires a user. If you don’t have users just feel free to comment the belongs_to :user line in the comment.rb file.

    I did test this with Rails 1.2.2 on two separate machines and ‘it is working on my machine…’ :)

  4. Posted February 19, 2007 at 9:51 pm | Permalink

    How can I do counter caching with acts_as_commentable? Not sure how that works with polymorphic relationships. Currently I am summarizing comment counts quite often which is leading to a lot of extra db queries. Thanks!

  5. Posted February 20, 2007 at 10:56 am | Permalink

    Just wanted to let you know that I was getting feedback from my users that comment text was being cutting off. I changed the comment field to be type text and the issue is fixed. Otherwise, a great plugin. Thanks!

  6. Posted February 20, 2007 at 5:22 pm | Permalink

    @carlivar – You can have a summary table for you model which might have a count of the comment for that model. The summary table is not part of the plugin, so at this time you would need to manage that…

    @bmctigue – The migration in the README used to have comment as a string type this has been modified to describe the comment as a text for a while now. Sorry for any inconvenience that might have caused.

  7. Posted February 21, 2007 at 3:44 pm | Permalink

    Thank you. Small feature request? It would be nice to be able to turn built-in rails counter caching on? Something like:

    acts_as_commentable, :counter_cache => true

  8. Posted March 2, 2007 at 6:28 pm | Permalink

    Hi

    Many thanks for this neat plugin. I needed comments on comments [multi level].

    I changed Comment itself to be acts_as_commentable and it works just fine. Do you see any problems with this approach?

    anand

  9. matthibcn
    Posted March 27, 2007 at 5:35 am | Permalink

    I do get => undefined method ‘find_commentable’ for Comment:Class following this example from Comments on Acts as Commentable found via SWik.

    In my model.rb I do have added acts_as_commentable, also the values commentable / commentable_id are set and post correctly reflecting the model in question…

  10. matthibcn
    Posted March 27, 2007 at 5:45 am | Permalink

    Never mind, in my enthusiasm I added an CommentModel to my app before reading further yesterday night and then forgot about it at all..so it was overwriting the plugins modelClass..it works as promised ;)

    Thx and regards

  11. matthibcn
    Posted March 27, 2007 at 3:10 pm | Permalink

    Ok, now I do have an issue.

    Where do you get the property “comments” from for a given model ??

    reading on this page and the forumentry I posted above I understand I would get all comments belonging to an ég. item just by doing:

    @comments = @item.comments

    This method isnt veen executed looking at the logfile, nor I dont see any method in your plugin called “comments” so I just wonder where it should come from

    on the other side, I also dont get a “method not found “exception” what makes me wonder also

  12. Posted April 17, 2007 at 4:15 pm | Permalink

    @famoseagle: I was thrown back by the same bug as you today and I think I found the problem: Since plugin code doesn’t get reloaded on every request, the comment model saves the object type of the user model at “load time”, but the user model gets reloaded at every request (at least in development mode) and so the user model gets a new object_id every time and this is not reflected in the comments model association.

    The error message is funny, but User and User are really two different things, then. One solution is to move comment.rb to app/models/, since then it will be reloaded, too and all is synchronized.

    A more complete description can be found at

    http://localhost3000.de/2007/04/17/acts_as_commentable-reload-fubar/

    Hope it helps.

  13. Posted April 17, 2007 at 8:08 pm | Permalink

    Jan,
    Thank you very much. That is exactly what I did … Stripped out all the extra garbage and moved it into my app. Very interesting issue though… I will have to keep that one in my back pocket. Thanks for the heads up.
    Casey

  14. Mark
    Posted April 28, 2007 at 5:36 pm | Permalink

    After upgrading to rails 1.2.3 I am occasionally getting the following error when accessing the comments for a model that acts_as_commentable.

    undefined method `table_name’ for REXML::Comment:Class

    It appears that the wrong Comment class is being referenced. Has anybody else seen this? Does anybody know how to fix it?

    Thanks,
    Mark

  15. Posted May 13, 2007 at 11:17 am | Permalink

    My dirty little hack to use counter_cache while you guys don’t come up with a new release:

    http://www.hervalfreire.com/blog/2007/05/13/caching-comments-with-acts_as_commentable/

  16. Posted May 19, 2007 at 3:15 pm | Permalink

    I sexy’d up that migration for Rails 2.0 or the Sexy_Migration plugin:

    def self.up
      create_table :comments, :force => true do
        string :title, :limit => 50, :default => ""
        string :comment, :default => ""
        timestamps!
        polymorphic :commentable
        foreign_key :user
      end
    
      add_index :comments, ["user_id"], :name => "fk_comments_user"
    end
    
    def self.down
      drop_table :comments
    end
    
  17. Lance Carlson
    Posted July 8, 2007 at 10:54 am | Permalink

    Hey I love the plugin. Was just wondering if you or I could make a generator for the migrations and stick them inside the repo. I think it will make the installation just that much easier :)

  18. Andrew Gordon
    Posted July 12, 2007 at 4:05 am | Permalink

    Great plugin thanks

  19. Andrew Gordon
    Posted July 17, 2007 at 2:23 pm | Permalink

    [new to rails] and being stupid, but how do i get the name of the user who added the comment, i have a partial that displays the comment and thought i would enter somthing like but this dont work.

    I am using acts_as_authenticated, can anyone help me?

  20. Evan
    Posted August 2, 2007 at 1:01 pm | Permalink

    Andrew -

    You should be able to make use of the model associations (ie, has_many: , belongs_to:, etc) to pull in the name of the user from another table. An example:

    ” class=”comment_bar”>
    ” class=”comment_header”> ()
    ” class=”comment_body”>

  21. Evan
    Posted August 2, 2007 at 4:46 pm | Permalink

    Hmm. The cut and paste didn’t translate well.

    Lets say that I have a photo model using acts_as_commentable, which is associated to the user model with belongs_to: / has_many:

    I would do something to this effect in the view:

    for p in @photo.comments
    … p.user.realname
    … p.user.email

    (etc)

  22. Soleone
    Posted January 3, 2008 at 12:35 am | Permalink

    Very good plugin, because it’s easy to install and use, and also easy to change since it’s so small.

    Note: The sexy migration (Rails 2.0 style) posted here does not work and needs some changes first.

  23. Posted January 25, 2008 at 8:30 pm | Permalink

    Nice plugin, I plan on using it for a project I’m working on. One thing you could add with little effort is a fixture. acts_as_taggable_on_steroids has a good example- it’d be like 1 line in your test file and yaml file with some default data.

    either way, nice job, keep up the good work.

  24. Posted February 12, 2008 at 10:55 am | Permalink

    Awesome plugin! If you’d like to map the comments table to a non-standard user foreign key but aren’t sure where to start, I wrote up a short blog post about it: Using acts_as_commentable with a non-standard user foreign key

    Hope this helps somebody!

  25. Vipin
    Posted February 18, 2008 at 3:48 am | Permalink

    Hey guys,
    Is there any way to integrate attachment_fu plugin with in Acts As Commentable Plugin? i want to add more than 1 image for a comment. how can i do it?
    thanks in advance
    Vipin

  26. Posted March 4, 2008 at 5:44 pm | Permalink

    This is the migration I used for Rails 2.0 (mostly sexy migrations)

      def self.up
        create_table :comments, :force => true do |t|
          t.string :title, :default => ""
          t.text :comment, :default => ""
          t.timestamps
          t.integer :user_id, :default => 0, :null => false
          t.string :web_site
          t.string :email
          t.string :name
          t.references :commentable, :polymorphic => true
        end
        add_index :comments, ["user_id"], :name => "fk_comments_user"
      end
    
  27. Posted April 29, 2008 at 1:56 pm | Permalink

    Is there a way to incorporate this with paperclip?

    I added has_attached_file to the comment.rb and followed directions but its not saving the file. It keeps coming up blank.

  28. Keith Carter
    Posted November 14, 2008 at 10:54 am | Permalink

    Is there a way to eager load the objects associated with comments?

  29. Posted November 18, 2008 at 8:37 am | Permalink

    2 years of superior plugin ! :)

  30. Posted November 18, 2008 at 9:39 am | Permalink

    I just remember year ago i put this plugin in rails 1.2.6 .. now in 2.1.2 :)

  31. Fran
    Posted February 12, 2009 at 4:21 am | Permalink

    Herval’s dirty little hack to use counter_cache (site is down):

    #comments.rb
    
    def after_create
     if commentable.attributes['comments_count']
      commentable.increment!(”comments_count”)
     end
    end
    
    def before_destroy
     if commentable.attributes['comments_count']
      commentable.class.decrement_counter(”comments_count”, commentable.id)
     end
    end
    
  32. Auraelius
    Posted April 16, 2009 at 11:37 am | Permalink

    Hi,
    I’m having trouble when using acts_as_commentable with restful_authentication: The user_id field in the comment table is never getting set — all the values are NULL.

    I have a “users” table as supplied by that plugin. Is acts_as_commentable looking for a “user” table? I’m still trying to understand all of Rails’ pluralization.

    Where in the code does the user_id get set? I’m stepping through the process with a debugger and can’t see it happening. Is this something ActiveRecord does?

    Thanks for helping a newbie figure things out!

  33. Jeff Tucker
    Posted June 24, 2009 at 1:59 pm | Permalink

    Thanks for the plugin! One issue I had when installing though — I grabbed the gem from your most recent commit (19 May 2009) and had the error:

    Expects acts_as_commentable.rb to define ActsAsCommentable (LoadError).
    

    I had to add

    require 'comment_methods'
    

    to the top of lib/acts_as_commentable.rb to get everything running.

  34. Posted June 24, 2009 at 3:39 pm | Permalink

    @Jeff – Thanks for that info, I test this on a more recent Rails version. I can’t believe it, but this plugin was originally written in Rails 1.2 and now there is talk of Rails 3.0.

13 Trackbacks

  1. [...] primero es Acts as Commentable que, cómo indica su nombre, permite marcar los modelos Rails como comentables. No hay nada más [...]

  2. [...] certainly benefited from plugins in our Rails development, using some really useful plugins like acts_as_commentable, attachment_fu and [...]

  3. By Food for thought : Useful URLs for RoR 2.0 on December 18, 2007 at 6:56 am

    [...] acts_as_commentable plugin [...]

  4. [...] my contribution (with gratitude to acts_as_commentable) – you can now comment on a suggestion.  Because the meaning of a suggestion isn’t always [...]

  5. By acts_as_commentable for noobs (like me) on March 24, 2008 at 12:24 am

    [...] was working on adding a commenting system to the site and all my web searches pointed to the acts_as_commentable Rails plugin. Now since I’m a noob, I didn’t understand how to use most of it, but I finally pieced [...]

  6. By BrewSession Blog » belong_to RSpec matcher on April 12, 2008 at 8:03 pm

    [...] was extending acts_as_commentable and needed a good RSpec test to check the returned objects from its finder methods belonged to the [...]

  7. By BrewSession Blog » Extending acts_as_commentable on April 12, 2008 at 11:49 pm

    [...] acts_as_commentable is a nice little plugin. It extends your AR classes giving them comments. We are going to use comments on all kinds of things, starting with recipes, of course. However, AAC lacks a critical feature: the ability for users to approve comments before they are displayed. In this post I am going to run through extending AAC using acts_as_state_machine. [...]

  8. [...] acts_as_commentable for comments on your user profiles and blog posts [...]

  9. [...] os criadores do acts_as_commentable não lançam uma nova versão do plugin com suporte a counter_caches, aqui vai um pequeno truque [...]

  10. [...] Acts_as_commentable [...]

  11. By VenkelSC on October 14, 2008 at 1:24 pm

    [...] ruby script/plugin install http://svn.techno-weenie.net/projects/plugins/white_list/ * Sistema de comentarios: Acts_as_commentable [...]

  12. By Getting Close on January 20, 2009 at 7:52 pm

    [...] the acts_as_commentable plugin to the newest version. This allows me to streamline the code and add times to the [...]

  13. By AJAX with acts_as_commentable — sideline on February 15, 2009 at 11:14 am

    [...] had fun this weekend with AJAX-ifying an implementation of the acts_as_commentable plugin. After reading (and implementing) Dave Naffis’ article on adding AJAX to the [...]

Post a Comment

Your email is never published nor shared. Required fields are marked *

*
*