views:

79

answers:

2

I would like to allow users to write comments on a site. If they are registered users their username is displayed with the comment, otherwise allow them to type in a name which is displayed instead.

I was going to create a default anonymous user in the database and link every non-registered comment to that user. Would there be a better way to do it?

Any advice appreciated.

Thanks.

+1  A: 

I think you can make user_id on your comment model nullable since you want to allow non registered users to add comments as well. As far as adding names for the non registered users are concerned, there are two options for that

option 1. Add a column on Comment model and name it like anonymous_user where you will store names of non registered users

option 2. Create a another model AnonymousCommentor with name and comment_id attributes.

If you are going to use anonymous users for other things as well apart from comment in your application then you can make it polymorphic and use a suitable name like AnonymousUser instead of AnonymousCommentor

nas
+2  A: 

The problem with creating an anonymous user is then you need to check if a comment was made by a "real" user, or an anonymous one when displaying the name, so that introduces complexity. Plus, if you have a way of viewing their profile page, which may include posting history, you'd need to exclude the anonymous user with an exception.

Generally it's better to have a column on your comments which represents the user's visible name, and just show that if provided, or the registered user's name otherwise. For instance, your view helper might look like this:

class Comment < ActiveRecord::Base
  belongs_to :user

  def user_name
    self.anonymous_name or (self.user and self.user.name) or 'Anonymous'
  end
end

This will display the contents of the anonymous_name field of the Comment record, or the user's name if a user is assigned, or 'Anonymous' as a last-ditch effort to show something.

Sometimes it's advantageous to actually de-normalize a lot of the database when dealing with large numbers of comments so you don't have to load in the user table via a join simply to display a name. Populating this field with the user's name, even if they're not anonymous, may help with this, though it does mean these values need to be updated when a username changes, presuming that's even possible.

tadman