为 Rails 模型定义外键关系 [英] Defining foreign key relationships for Rails' models

查看:13
本文介绍了为 Rails 模型定义外键关系的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 Post 类中有一个带有 post_id 的 :foreign_key 的 Comment 类.

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

但我的 CreateComments 迁移没有定义数据库级外键:

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

相反,post_id 是一个简单的整数列.

Instead post_id is a simple Integer column.

所以,这种外键关系似乎只存在于 Rails 的头脑中,而不存在于数据库层面.

这对吗?

另外,对应的 Post 模型是否也需要使用 :foreign_key 属性声明其与 Comments 的互惠外键关系,还是可以省略?

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

推荐答案

Rails 默认行为是模型上用于保存外键的列是带有后缀_id 添加.:foreign_key 选项允许您直接设置外键的名称.PostComment 模型类之间的关联应如下所示:

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

—注意你不需要 :class_name =>在您的 Comment 模型中发布".Rails 已经有了这些信息.只有在需要覆盖 Rails 的约定时,才应该指定 :class_name:foreign_key.

—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.

Rails 为您维护外键关系是正确的.如果需要,可以通过添加外键约束在数据库层强制执行它们.

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.

这篇关于为 Rails 模型定义外键关系的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆