【发布时间】:2014-02-15 03:53:10
【问题描述】:
我在我的 rails 4 应用程序上设置了一个设计。我按照本教程https://github.com/plataformatec/devise/wiki/How-To:-Allow-users-to-sign-in-using-their-username-or-email-address 并添加了用户名值。我还想要名字和姓氏,所以我认为它与教程很接近。我遵循了一些部分并跳过了身份验证部分,并更新了视图。它有点工作。注册字段时显示并且当您填写时,它们通过了所有检查,但它们不会进入数据库。它只是为名字和姓氏显示 NULL,但用户名实际上是有效的。以下是我执行的步骤。
我遵循了整个教程(除了关于 gmail 和 me.com 的最后一部分)。
我添加了名字和姓氏字段:
我运行了命令
rails generate migration add_firstname_to_users first_name:string:uniq
rails generate migration add_lastname_to_users last_name:string:uniq
然后rake db:migrate。然后我将这些字段添加到应用程序控制器以允许这些字段。这是我完整的application_controller.rb
class ApplicationController < ActionController::Base
# Prevent CSRF attacks by raising an exception.
# For APIs, you may want to use :null_session instead.
protect_from_forgery with: :exception
before_filter :configure_permitted_parameters, if: :devise_controller?
protected
def configure_permitted_parameters
devise_parameter_sanitizer.for(:sign_up) { |u| u.permit(:first_name, :last_name, :username, :email, :password, :password_confirmation, :remember_me) }
devise_parameter_sanitizer.for(:sign_in) { |u| u.permit(:login, :username, :email, :password, :remember_me) }
devise_parameter_sanitizer.for(:account_update) { |u| u.permit(:first_name, :last_name, :username, :email, :password, :password_confirmation, :current_password) }
end
end
然后我将名字和姓氏添加到attr_accessor。这是我完整的user.rb 模型。
class User < ActiveRecord::Base
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
attr_accessor :login, :first_name, :last_name
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable, :authentication_keys => [:login]
def self.find_first_by_auth_conditions(warden_conditions)
conditions = warden_conditions.dup
if login = conditions.delete(:login)
where(conditions).where(["lower(username) = :value OR lower(email) = :value", { :value => login.downcase }]).first
else
where(conditions).first
end
end
end
然后我更新了我的视图并将 <%= f.text_field :first_name %> 和 <%= f.text_field :last_name %> 添加到了注册新视图和注册编辑视图中。
提交表单时,这些字段会显示并且没有错误。他们只是不更新数据库。我通过 PHPMyAdmin 在 MYSQL 数据库中手动添加了名称,然后转到编辑页面,它正确地抓取了它。如果您能提供帮助,那就太好了。谢谢! :)
【问题讨论】:
标签: mysql ruby-on-rails devise ruby-on-rails-4