簡體   English   中英

Ruby on Rails:如何使用字符串作為主鍵創建對數據庫表的引用

[英]Ruby on Rails: how to create a reference to a db table with string as primary key

我是 ROR 的新手,現在正在做一個與書籍相關的課程項目。 我有一個以字符串“isbn”作為主鍵的“書”表,現在嘗試添加另一個“注釋”,引用帶有外鍵“isbn”的書表來引用“書”表。 所以我的“models/comment.rb”看起來像這樣:

class Comment < ApplicationRecord
  belongs_to :book, references: :isbn, type: :string
end 

而“models/book.rb”是:

class Book < ApplicationRecord
  has_many :comments, dependent: :destroy
end

我的“書”表如下所示: 書籍表的 SQLite 視圖 我希望生成的“comments”表在數據庫遷移后將包含一個列“isbn”(字符串),但實際上生成的“comments”表包含一個“book_id”(整數)。 在此處輸入圖像描述 如何生成外鍵來引用“book”表中的字符串主鍵“isbn”?

首先將外鍵列設置為正確的類型,並將外鍵約束設置為指向右列:

class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t|
      t.string :title
      t.string :note
      t.references :book, type: :string, column_name: :isbn
      t.timestamps
    end
  end
end

我希望生成的“comments”表在數據庫遷移后將包含一個列“isbn”(字符串),但實際上生成的“comments”表包含一個“book_id”(整數)。

遷移實際上比您想象的要簡單和愚蠢得多。 它只是一個創建 SQL 語句的 DSL。 它實際上並沒有以任何方式知道另一個表,因此它無法知道books.isbn是一個字符串列。 它只是使用add_reference的默認類型,即:integer Rails 是由慣例驅動的,而不是人工智能。

如果您想將該列稱為book_isbn之類的其他名稱,則必須分兩步進行:

class CreateComments < ActiveRecord::Migration[6.0]
  def change
    create_table :comments do |t|
      t.string :title
      t.string :note
      t.string :book_isbn
      t.timestamps
    end
    add_foreign_key :comments, :books, 
       column: "book_isbn", primary_key: "isbn"
  end
end

然后設置書籍 model 以使用您的非常規主鍵:

class Book < ApplicationRecord
  self.primary_key = :isbn
  has_many :comments, 
    foreign_key: :book_isbn # default is book_id
end

在評論方面,您需要配置belongs_to關聯,使其指向books.isbn而不是books.id

class Comment < ApplicationRecord
  belongs_to :book, primary_key: :isbn
end

references不是belongs_to的有效選項。

ArgumentError (Unknown key: :references. Valid keys are: :class_name, :anonymous_class, :foreign_key, :validate, :autosave, :foreign_type, :dependent, :primary_key, :inverse_of, :required, :polymorphic, :touch, :counter_cache, :optional, :default)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM