无法使用Rails和Devise中的自联接关系用户表创建新记录

时间:2017-01-19 17:17:41

标签: ruby-on-rails ruby-on-rails-5

我的rails应用程序出了问题。这是我模型中的代码:

    class User < ApplicationRecord
  has_many   :assistants,  class_name: User, foreign_key: :manager_id
  belongs_to :manager, class_name: User

  # Include default devise modules. Others available are:
  # :confirmable, :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  #validation       
  validates :first_name, :middle_name, :last_name, :birth_date, presence: true


end

这是我的迁移:

    class AddReferenceToUserTable < ActiveRecord::Migration[5.0]
  def change
    add_column :users, :manager_id, :integer
  end
end

但这是我的视图中的错误:

注册 1错误禁止此用户被保存: 经理必须存在

我可能知道我的代码有什么问题吗?

谢谢, Randz

1 个答案:

答案 0 :(得分:3)

如果这是rails 5应用程序所属,则默认需要。如果用户不总是有经理那么你想要

belongs_to :manager, class_name: User, required: false