簡體   English   中英

創建新的遷移時,Rails Mysql2 :: Error表不存在

[英]Rails Mysql2::Error Table doesn't exist When create new migration

我用以下代碼編寫了遷移(創建名為sources新表):

class CreateSources < ActiveRecord::Migration
  def change
    create_table :sources do |t|
      t.string :name, null: false, default: ""

      t.timestamps null: false
    end
  end
end

然后,我修改了現有模型:

class Property < ActiveRecord::Base
  validates :source, allow_blank: true, inclusion: { in: 
  Source.all.map{ |source| source.name } }

我想將驗證添加到屬性的源中,以僅允許源表中的sources

然后,當我運行遷移時,出現以下錯誤:

ActiveRecord::StatementInvalid: Mysql2::Error: Table 'sources' doesn't exist: SELECT `sources`.* FROM `sources`

問題是尚未初始化源表時發生查詢。
關於如何使遷移運行的任何提示?
這是在生產級別上運行的。 因此我可能無法刪除所有遷移並重新安排它。

Rails版本4.2.5
SQL版本5.7

請記住,您的Source.all.map{ |source| source.name } 當加載Property類時,將執行Source.all.map{ |source| source.name } 此時可能無法正確初始化Source類,並且可能未建立正確的數據庫連接。 此外,您將只能訪問Source.all一次,因此,如果添加了新Source則必須重新啟動應用程序。

相反,請手動驗證:

class Property < ActiveRecord::Base
  validate :valid_source
private
  def valid_source
    return if(source.blank?)
    return if(Source.where(name: source).exists?)
    errors.add(:source, 'Unknown source') # Or whatever you want to say
  end
end

這樣,您可以在正確的時間檢查sources表。

另外,我不希望您在遷移中看到該錯誤。 也許要避免在遷移中使用模型。

belongs_to :source ,您是否沒有特定的原因來代替您的belongs_to :source 像這樣復制名稱非常容易出錯,使用引用(希望由數據庫中的外鍵支持)會更安全。

您是否定義了源模型? 希望如此。

在這里,問題看起來像在運行遷移之前優先加載Property類,因此出現了問題。

暫無
暫無

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

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