由于 belongs_to 关系,设计不会保存到数据库
Devise will not save to database due to belongs_to relationship
在 Rails 应用程序中将标记行添加到我的 Devise 用户模型后,我无法再通过 Web 表单或在控制台上使用 User.create() 创建新用户。注释掉此行可恢复全部功能。显然它与上面的行密切相关,这样我就可以将用户分配给经销商。在我需要此功能时,有关于如何修复或以不同方式执行的任何建议吗?
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :registerable
has_many :tanks, dependent: :destroy
has_many :properties, dependent: :destroy
has_many :contacts, dependent: :destroy
has_many :stations
has_many :clients, :class_name => 'User', :foreign_key => :manager_id
belongs_to :dealer, :class_name => 'User' #<--- this one
end
belongs_to :dealer, :class_name => "User",foreign_key: "dealer_id", optional: true
注意:- 确保在 User
模型中也应该有 dealer_id
以使其正常工作 @user.dealer if @user.dealer.present?
Reason
- 在Rails 5中,每当我们定义一个
belongs_to association
时,默认情况下需要有关联的记录。
在 Rails 应用程序中将标记行添加到我的 Devise 用户模型后,我无法再通过 Web 表单或在控制台上使用 User.create() 创建新用户。注释掉此行可恢复全部功能。显然它与上面的行密切相关,这样我就可以将用户分配给经销商。在我需要此功能时,有关于如何修复或以不同方式执行的任何建议吗?
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable, :registerable
has_many :tanks, dependent: :destroy
has_many :properties, dependent: :destroy
has_many :contacts, dependent: :destroy
has_many :stations
has_many :clients, :class_name => 'User', :foreign_key => :manager_id
belongs_to :dealer, :class_name => 'User' #<--- this one
end
belongs_to :dealer, :class_name => "User",foreign_key: "dealer_id", optional: true
注意:- 确保在 User
模型中也应该有 dealer_id
以使其正常工作 @user.dealer if @user.dealer.present?
Reason
- 在Rails 5中,每当我们定义一个
belongs_to association
时,默认情况下需要有关联的记录。