Defining Foreign Key Relationships for Rails Models

I have a Comment class with: foreign_key from post_id in the Post class.

class Comment < ActiveRecord::Base belongs_to :post, :class_name => "Post", :foreign_key => "post_id", :counter_cache => true belongs_to :author, :class_name => "User", :foreign_key => "author_id" end 

But my transfer of CreateComments does not define a foreign key at the database level:

 class CreateComments < ActiveRecord::Migration def self.up create_table :comments do |t| t.column "post_id", :integer, :default => 0, :null => false t.column "author", :string, :default => "", :limit => 25, :null => false t.column "author_email", :string, :default => "", :limit => 50, :null => false t.column "content", :text, :null => false t.column "status", :string, :default => "", :limit => 25, :null => false t.timestamps end end def self.down drop_table :comments end end 

Instead of post_id, a simple Integer column.

So it looks like this foreign key relationship exists only in the Rails mind, and not at the database level.

Is it correct?

In addition, it is necessary that the corresponding Post model also declares its foreign key relationship with comments using the attribute: foreign_key or can it be omitted?

 class Post < ActiveRecord::Base set_table_name("blog_posts") belongs_to :author, :class_name => "User", :foreign_key => 'author_id' has_many :comments, :class_name => "Comment", :foreign_key => 'post_id', :order => "created_at desc", :dependent => :destroy has_many :categorizations has_many :categories, :through => :categorizations named_scope :recent, :order => "created_at desc", :limit => 5 end 
+48
ruby-on-rails foreign-keys
May 24 '09 at 18:50
source share
1 answer

The default behavior of Rails is that the column used to store the foreign key in the model is the name of the association with the suffix _id added. Parameter :foreign_key allows :foreign_key to directly specify the name of a foreign key. The associations between your Post and Comment classes should look like this:

 class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end 

- Please note that you do not need :class_name => "Post" in your Comment model. Rails already has this information. You should only specify :class_name and :foreign_key when you need to override Rails conventions.

You are right that Rails maintains a relationship with a foreign key for you. You can force them at the database level if you want by adding foreign key constraints.

+69
May 24 '09 at 19:07
source share



All Articles