My app allows users to register and login but it also allows anyone to add comments, regardless of whether they are registered or not.
I have a comment table and a user table and I’d like to store the name and home page url of the comment author.
If the user is registered, then the comment needs a foreign key back to the registered user. But if the comment was posted anonymously, then I need to record the author name and url directly in the comment table. My comments table ends up with both:
class CreateComments < ActiveRecord::Migration
create_table :comments do |t|
t.column :comment, :text
t.column :article_id, :integer
t.column :user_name, :string #only used if user_id is empty
t.column :user_url, :string #only used if user_id is empty t.column :user_id, :integer #when populated, user_name and user_url are ignored end
Then in my code when I need to find the author of the comment, I check the comment’s user_id and either get the author from the user record (user.name) or from the comment directly (user_name).
My question: Does rails have any mechanism for automatically getting the data either from a foreign key or directly from the record? Such a mechanism would save me from checking the foreign key to determine where the data should come from. Or perhaps there is a better database design for this situation?