This time, we're adding comments to our Photo model, as presented in the elegant permalinks post. First of all, I looked for a gem to do this job for us, and found acts_as_commentable. Its setup goes something like this:
Add the gem to our Gemfile, and run `bundle install`:
gem 'acts_as_commentable'Generate the tables and migrate the DB:
$ rails g comment $ rake db:migrateAdd the comments to our Photo model:
class Photo < ActiveRecord::Base acts_as_commentable endBy doing this, we get the following interface to the comments in our photos:
commentable = Photo.create comment = commentable.comments.create comment.title = "First comment." comment.comment = "This is the first comment." comment.save commentable = Post.find(1) comments = commentable.comments.recent.limit(10).allHowever, this solution, while adding another dependency to a gem, does not give us some functionality we would like to have: the comments are not linked to the users, we have to set up the controller by hand, views and json interface is missing…
A simpler solution, without any gem, is creating the comments as a tipical ActiveRecord model, harnessing the (often overlooked) power of the Rails generators:
As I said on the original post, this guide is meant to make the most of the Rails gem ecosystem. In this case, though, creating the feature ourselves is actually faster, while not bringing a new dependency to our app, and giving us more control over our code.
Tune up next for how to add notifications to our social network, coming soon!