big*_*cup 1 sqlite ruby-on-rails foreign-keys
我正在使用Sqlite开发Rails应用程序,并且有一个与其他几个表关联的用户表。尝试在Users中重命名列时,运行rails db:migrate时出现主题错误。
我在这里看到很多类似问题的帖子,但没有一个奏效。具体来说,常见的补救方法似乎是在所有has_many和has_one关联上使用“ dependent::destroy”。我正在这样做,但是仍然出现错误。
我究竟做错了什么?
下面是我的代码:
class User < ApplicationRecord
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_one :profile, dependent: :destroy
has_many :bikes, dependent: :destroy
has_many :bookings, dependent: :destroy
has_many :rented_bikes, through: :bookings, source: :bike
has_many :conversations, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :liked_bikes, through: :likes, :source => :bike
has_many :viewed_bikes, through: :views, :source => :bike
has_many :views, dependent: :destroy
has_many :reviews, dependent: :destroy
end
class Profile < ApplicationRecord
belongs_to :user
end
class Bike < ApplicationRecord
belongs_to :user
has_many :images, dependent: :destroy
has_many :bookings, dependent: :destroy
has_many :booked_users, through: :bookings, source: :user
has_many :conversations, dependent: :destroy
has_many :likes, dependent: :destroy
has_many :liking_users, :through => :likes, :source => :user
has_one :amenity, dependent: :destroy
has_many :places, dependent: :destroy
has_many :views, dependent: :destroy
end
class Booking < ApplicationRecord
belongs_to :bike
belongs_to :user
has_one :review, dependent: :destroy
validates :date_start, presence: true
validates :date_end, presence: true
validates :user_id, presence: true
end
class Conversation < ApplicationRecord
belongs_to :user
belongs_to :bike
has_many :messages, dependent: :destroy
end
class Like < ApplicationRecord
belongs_to :user
belongs_to :flat
end
class View < ApplicationRecord
belongs_to :user
belongs_to :flat
end
class Review < ApplicationRecord
belongs_to :user
belongs_to :booking
end
Run Code Online (Sandbox Code Playgroud)
移民:
class ChangeCustomerIdToUserId < ActiveRecord::Migration[5.1]
def change
rename_column :users, :customer_id, :client_id
end
end
Run Code Online (Sandbox Code Playgroud)
您一次遇到了几个问题:
users表的其他表中有外键。(2)是在迁移期间触发您的错误的原因:当有外键引用该表时,您不能删除该表(请参阅(1)),因为删除该表会违反那些外键。
解决方案是删除迁移中所有有问题的FK,然后执行rename_column,然后再次添加所有FK。或者更好的是,停止使用SQLite来支持具有对列重命名的适当支持的更好的数据库(例如PostgreSQL或MySQL或要在其上部署应用程序的任何数据库)。另一种选择是尝试在迁移过程中关闭FK并将其重新打开,例如:
connection.execute("PRAGMA defer_foreign_keys = ON")
connection.execute("PRAGMA foreign_keys = OFF")
rename_column :users, :customer_id, :client_id
connection.execute("PRAGMA foreign_keys = ON")
connection.execute("PRAGMA defer_foreign_keys = OFF")
Run Code Online (Sandbox Code Playgroud)
可能有用。
三个月前对Rails进行了一次提交,应该可以解决此问题,但我认为它尚未成为任何发行版。