我正在使用Sqlite在Rails应用程序上工作,并且将一个users表与其他几个表相关联。尝试在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
迁移:
class ChangeCustomerIdToUserId < ActiveRecord::Migration[5.1]
def change
rename_column :users, :customer_id, :client_id
end
end
答案 0 :(得分:6)
您一次遇到了几个问题:
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")
可能会工作。
三个月前,有一个commit made to Rails应该可以解决此问题,但我认为它尚未成为任何发行版。