[英]SQLite migration removes 'add_index' and 'add_foreign_key' from schema.rb file
我在同一Rails項目上但在兩台不同的計算機上使用SQLite3和MySQL。 我注意到,在我運行所有遷移時生成的schema.rb
在兩種環境下看起來都不同。 當我在SQLite3環境中運行遷移時,以下語句已從 schema.rb
文件中刪除 。
add_index "places", ["user_id"], :name => "places_user_id_fk"
add_foreign_key "places", "users", :name => "places_user_id_fk"
請注意,我使用的外國人gem通過add_foreign_key
和remove_foreign_key
擴展了遷移。
以下是與問題相關的遷移和模型:
# 20130123004056_create_places.rb
class CreatePlaces < ActiveRecord::Migration
def change
create_table :places do |t|
t.string :name
t.string :location
t.integer :user_id
t.timestamps
end
end
end
...
# 20130123234250_add_foreign_key.rb
class AddForeignKey < ActiveRecord::Migration
def change
add_foreign_key(:places, :users)
end
end
...
# user.rb
class User < ActiveRecord::Base
has_many :places
end
...
# place.rb
class Place < ActiveRecord::Base
belongs_to :user
end
問題:如何以SQLite3和MySQL都可以處理的方式定義users
與places
之間的關系?
foreigner
README明確指出
支持以下適配器:
- sqlite (外鍵方法是禁止操作的)
因此您的SQLite數據庫沒有設置外鍵約束, 因為foreigner
不支持它們 。 從SQLite數據庫生成db/schema.rb
,這就是為什么未指定外鍵的原因。
《 Rails遷移指南》中提到了很多外鍵
如果您需要執行特定於數據庫的任務(例如,創建外鍵約束),那么
execute
方法允許您執行任意SQL
甚至還有一個有關如何添加/刪除外鍵的示例。
剛開始使用Rails時曾使用過foreigner
,建議您將其從Gemfile
,或者
execute
遷移方法(並確保所有不同的RDBMS都支持您在execute
方法中添加的內容) 正如您在評論中所指出的那樣 ,SQLite在創建表后缺乏對添加外鍵的支持; 無法通過在Rails中進行進一步遷移來添加它們。 我個人建議您使用選擇1或3 ,因為在滿足SQLite限制的遷移中通過execute
命令創建解決方案將更加困難,而在其他RDMS上具有相同的最終結果。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.