Defining foreign key relationships for Rails' models

前端 未结 1 685
孤独总比滥情好
孤独总比滥情好 2020-12-12 16:07

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\"         


        
相关标签:
1条回答
  • 2020-12-12 16:33

    The Rails default behaviour is that the column used to hold the foreign key on a model is the name of the association with the suffix _id added. The :foreign_key option lets you set the name of the foreign key directly. The associations between your Post and Comment model classes should look like this:

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

    —Note that you don't need :class_name => "Post" in your Comment model. Rails already has that information. You should only be specifying :class_name and :foreign_key when you need to override the Rails' conventions.

    You're correct that Rails maintains the foreign key relationships for you. You can enforce them in the database layer if you want by adding foreign key constraints.

    • I think you would benefit from reading A Guide to ActiveRecord Associations.
    0 讨论(0)
提交回复
热议问题