KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I have a Comment class with a :foreign_key of 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 CreateComments migration does not define a database-level foreign key: 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 post_id is a simple Integer column. So, it seems that this foreign key relationship exists only in the mind of Rails, not at the database level. Is this correct? Also, is it necessary for the corresponding Post model to also declare its reciprocal foreign key relationship with Comments using the :foreign_key attribute or could that 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
Tags (comma-separated)
Save Edits
Cancel