我正在使用Sqlite开发一个Rails应用程序,并有一个与其他几个表相关联的users表。当试图在用户中重命名列时,我在运行rails db:migrate时得到了主题错误。
我在这里看到了很多类似问题的帖子,但都没有奏效。具体来说,常见的补救方法似乎是对所有has_many和has_one关联使用“依赖::破坏”。我正在做这件事,但仍然会犯错误。
我做错了什么?
下面是我的代码:
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发布于 2018-08-13 05:31:48
你有几个问题同时发生:
users表的其他表中有外键。(2)是在迁移过程中触发错误的原因:当有引用外键的外键时,不能删除表(请参阅(1)),因为删除表会违反这些外键。
解决方案是删除迁移中所有违规的FKs,然后执行rename_column,然后再次添加所有FKs。另一种选择是尝试关闭FKs,并在迁移过程中重新打开它们,如下所示:
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")可能有用。
三个月前有一个提交到Rails可以解决这个问题,但我认为它还没有进入任何发行版。
https://stackoverflow.com/questions/51814399
复制相似问题