Skip to content

Thoughts on :foreign_key

December 8, 2010

Look at the models


class Topic < ActiveRecord::Base
  belongs_to :group
  belongs_to :creator, :class_name => "User"
  has_many :comments, :as => :commentable
end

class User < ActiveRecord::Base
  has_many :topics, :foreign_key => :creator_id
end

Now Topic has a field – creator_id meat to be used to point to the user who created the topic.

Thing is, I just did not expect has_many to need the :foreign_key specified to it. I expected Topic to need it. But theoretically, the foreign key can be deduced from the ‘belongs_to :creator’. so it is not required in the Topic model. However, it is required in the User model as shown in the above code

Advertisements

From → Uncategorized

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: