title: Defining foreign key relationships for Rails' models
body: <p>I have a Comment class with a :foreign_key of post_id in the Post class.</p>
  
  <pre><code>class Comment &lt; ActiveRecord::Base
    belongs_to :post, :class_name =&gt; "Post", :foreign_key =&gt; "post_id", :counter_cache =&gt; true
    belongs_to :author, :class_name =&gt; "User", :foreign_key =&gt; "author_id"
  end
  </code></pre>
  
  <p><strong>But my CreateComments migration does not define a database-level foreign key:</strong></p>
  
  <pre><code>class CreateComments &lt; ActiveRecord::Migration
    def self.up
      create_table :comments do |t|
        t.column "post_id",       :integer,   :default =&gt; 0, :null =&gt; false
        t.column "author",        :string,    :default =&gt; "",   :limit =&gt; 25, :null =&gt; false
        t.column "author_email",  :string,    :default =&gt; "",   :limit =&gt; 50, :null =&gt; false
        t.column "content",       :text,      :null =&gt; false
        t.column "status",        :string,    :default =&gt; "",   :limit =&gt; 25, :null =&gt; false
        t.timestamps
      end
    end
  
    def self.down
      drop_table :comments
    end
  end
  </code></pre>
  
  <p>Instead post_id is a simple Integer column. </p>
  
  <p><strong>So, it seems that this foreign key relationship exists only in the mind of Rails, not at the database level.</strong> </p>
  
  <p>Is this correct?</p>
  
  <p><strong>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?</strong></p>
  
  <pre><code>class Post &lt; ActiveRecord::Base
    set_table_name("blog_posts")
    belongs_to :author, :class_name =&gt; "User", :foreign_key =&gt; 'author_id'
    has_many :comments, :class_name =&gt; "Comment",
      :foreign_key =&gt; 'post_id', :order =&gt; "created_at desc", :dependent =&gt; :destroy
    has_many :categorizations
    has_many :categories, :through =&gt; :categorizations
    named_scope :recent, :order =&gt; "created_at desc", :limit =&gt; 5
  
  end
  </code></pre>