Search code examples
ruby-on-railsbelongs-tocomments

Commenting system for RoR Blogging Platform


I'm trying to design a comment system for my RoR blogging site, and I am having some conceptual problems with the architecture. As far as models are concerned, I have Blogposts, Users, and Comments.

  • A User has_many Blogposts
  • A Blogpost belongs_to one User
  • A Blogpost has_many Comments
  • A Comment may or may not belong to a registered User (I want people not registered with the site to be able to comment as well).

My question is this: in order to enforce the link between a comment and a blogpost, I create each new comment (@comment) through the blogpost association (@blogpost.comments.build(:args)). However, I do not know how to associate a particular registered User with his/her comment. I left the user_id attribute OUT of the attr_accessible for the Comment model because I wanted to prevent the possibility of people attributing comments to the wrong users.

Any ideas on how best to implement a commenting system with such a relation? Thanks so much in advance!


Solution

  • Assuming:

    User has_many comments
    Comment belongs_to user
    

    In your controller when saving the comment, you can simply do:

    @comment.user = current_user if current_user
    @comment.save
    

    If the comment is done by an unregistered user @comment.user just stays empty.