【问题标题】:How to override the default primary key column in ruby on rails 4.0.+?如何覆盖 ruby​​ on rails 4.0.+ 中的默认主键列?
【发布时间】:2016-03-01 19:14:22
【问题描述】:

我有一个已经存在的数据库架构,其中包含以字符串列作为主键的表以及一些以多个列作为键的表。我想在 rails 中映射这个模式,但我不知道如何覆盖默认主键(由 rails 框架创建的列 id)。

【问题讨论】:

    标签: ruby-on-rails overriding primary-key rails-models


    【解决方案1】:

    你可以像这样覆盖主键

    class Book < ActiveRecord::Base
      self.primary_key = 'author'
    end
    

    【讨论】:

    • 我在我的书中读到了这种方法,它说只覆盖列名,例如,rails 中主键的默认列名是 id,现在是它的作者,但数据类型仍然是整数。我的架构中有一个字符串作为主键,因此这不能解决我的问题。
    • Altering the primary key in Rails to be a string 以及为什么您应该尝试避免这样做
    【解决方案2】:

    我不知道你想做什么。在 Rails 中更改主键是错误的。

    但就此而言,请尝试在您的迁移中进行。

    class Foos < ActiveRecord::Migration  
        def self.up  
            create_table :foos, :id => false do |t|  
              t.string :my_id
              t.timestamps
            end
        end
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-10-25
      • 2016-07-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多