我有一个典型的场景, 我有两个模型用户和学生 用户has_one学生 学生belongs_to用户。 因此,当我在创建学生的同时,我正在创建一个与学生相关联的新用户 user = @ student.build_user 然后我无法使用该用户帐户登录。
应用程序/模型/ user.rb
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable #, :confirmable
before_save :set_default_role
attr_accessor :role, :password
has_one :student_admission, :class_name => "Student", :foreign_key=>"user_id"
private
def set_default_role
if self.new_record?
self.admin, self.student, self.employee = false, false, false
self.admin = true if self.role == 'Admin'
self.student = true if self.role == 'Student'
self.employee = true if self.role == 'Employee'
self.parent = true if self.role == 'Parent'
end
end
end
class Student < ActiveRecord::Base
belongs_to :user
before_validation :create_user_and_validate
def create_user_and_validate
if self.new_record?
user_record = self.build_user
user_record.first_name = self.first_name
user_record.last_name = self.last_name
user_record.email = self.email.to_s
user_record.password = self.admission_no.to_s + "123"
user_record.role = 'Student'
#user_record.email = self.email.blank? ? "" : self.email.to_s
check_user_errors(user_record)
return false unless errors.blank?
else
changes_to_be_checked = ['admission_no','first_name','last_name','email']
check_changes = self.changed & changes_to_be_checked
unless check_changes.blank?
self.user.username = self.admission_no if check_changes.include?('admission_no')
self.user.first_name = self.first_name if check_changes.include?('first_name')
self.user.last_name = self.last_name if check_changes.include?('last_name')
self.user.email = self.email if check_changes.include?('email')
check_user_errors(self.user)
end
end
end
def check_user_errors(user)
unless user.valid?
user.errors.each{|attr,msg| errors.add(attr.to_sym,"#{msg}")}
end
user.errors.blank?
end
def full_name
"#{first_name} #{middle_name} #{last_name}"
end
end
我想知道这是否可以使用devise登录这样的用户。如果是那么。请帮助,因为我是rails4的新手。 感谢