【问题标题】:Adding particular column as foreign key in rails migration在 Rails 迁移中添加特定列作为外键
【发布时间】:2016-02-11 20:56:22
【问题描述】:

我有两张桌子,ArticleArticle_metadata

我在这两个表之间添加了引用和外键。但是 rails 会有些方法将article_id(Article 表的 id 列)作为外键。

但我希望文章表中的另一列 (Article_uuid) 作为我的外键。我该怎么做 ?

这就是我现在的做法。在创建Article_metadata迁移文件中:

add_reference :article_metadata, :article, foreign_key: true

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-4 activerecord rails-migrations


    【解决方案1】:

    在您的 ArticleMetaData 类中,将自定义外键添加到 belongs_to 声明。这是一个例子:

    class ArticleMetaData < ActiveRecord::Base
      table_name "Article_metadata"
      belongs_to :article, foreign_key: "article_uuid"
    end
    

    add_reference 实际上创建了一个新列和索引,但听起来您的列已经存在,所以您不需要新的。

    要引用文章中的元数据,请修改文章模型以引用相同的 foreign_key 字段:

    class Article < ActiveRecord::Base
      # Tell ActiveRecord which column is the primary key (id by default)
      self.primary_key = 'uuid'
    
      # Tell the relationship which field on the meta_data table to use to match this table's primary key
      has_one :meta_data, foreign_key: "article_uuid", class_name: "ArticleMetaData"
    
    end
    

    【讨论】:

    • 如何检索特定文章的文章元数据?我可以做 Article.Article_metadata 吗?
    • 而新创建的外键列默认为整数数据类型,如何将数据类型设置为字符串或varchar?
    • 我进行了编辑以向您展示如何从文章中查找元数据。不知道您的模型名称实际上是什么,您可能需要对其进行一些调整,但其余的都很好。
    • 你太棒了,它有效。这个约束也会在数据库级别强制执行吗?
    • 您可以通过从迁移中添加索引来设置它。它看起来像:add_index :articles, :uuid, index: true, unique: true
    猜你喜欢
    • 1970-01-01
    • 2015-09-22
    • 2015-03-03
    • 1970-01-01
    • 1970-01-01
    • 2016-01-09
    • 1970-01-01
    • 1970-01-01
    • 2020-03-08
    相关资源
    最近更新 更多