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