Had my first interview with Thoughtbot today.  The interviewer asked me a question about how I would handle having comments for different objects in a discussion board (Posts, Images, Articles).  My answer was to have a bunch of foreign keys under a comments model/table.    

She said I should look into polymorphic associations.  I’d heard this term once before at Dev Bootcamp so it peaked my interest.

Polymorphic associations allow us to create just one Comment model and have each comment know which other model it should be associated with.

For example, instead of putting a bunch of different types of comment tables/models you can insert t.belongs_to :commentable, polymorphic: true into your migration which will create commentable_id and commentable_type columns in your comments table.  Jointly these serve as the foreign key for comments associated with several different tables.

Add belongs_to :commentable, polymorphic: true to the comments model to specify the polymorphic relationship.  On the other models add the has_many :comments, as: :commentable association in order to establish the relationship.

You then need to nest you routes:

resources :photos do 

  resources :comments

end

Now the route for all comments of photo.id 1 is http://localhost:3000/photos/1/comments

Your show action in your photos controller might look like this:

def show

  @photo = Photo.find(params[:id])

  @commentable = @photo 

  @comments = @commentable.comments 

  @comment = Comment.new

end