My app allows users to register and login but it also allows anyone to
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
home page url of the comment author.
If the user is registered, then the comment needs a foreign key back to
registered user. But if the comment was posted anonymously, then I need
record the author name and url directly in the comment table. My
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
Then in my code when I need to find the author of the comment, I check
comment’s user_id and either get the author from the user record
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
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