我正在尝试在 Camping 应用程序上实现身份验证系统,并且我对 User 模型进行了重大更改以将其合并,但现在我的 post 方法不会自动分配和 auto_incrememnt user_ids 到我的 User 类。
我正在尝试使用这些教程: http ://www.sitepoint.com/rails-userpassword-authentication-from-scratch-part-i/ http://www.sitepoint.com/rails-userpassword-authentication-from -scratch-part-ii/
我目前没有使用视图,我正在发送 HTTParty 帖子来创建用户,但是响应返回的 id 为 null 并且记录没有保存到数据库:
resp = "{\"id\":null,\"username\":\"testusername\",\"email\":null,\"encrypted_password\":null,\"salt\":null,\"password\":\"testpassword\",\"name\":\"testname\",\"github_login\":\"testgithub\",\"created_at\":null,\"updated_at\":null}"
任何人都可以帮助解决这个问题或让我走上正轨吗?谢谢你!
(很抱歉发布了这么多代码,我是 activerecord/camping 的新手,不知道我的错误可能在哪里。)
这是我的模型:
module Notepasser
include Camping::Session
end
module Notepasser::Models
class User < ActiveRecord::Base
EMAIL_REGEX = /\A[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}\z/i
include BCrypt
attr_accessor :password, :password_confirmation
has_many :sent_messages, :class_name => 'Message', :foreign_key => 'sender_id'
has_many :received_messages, :class_name => 'Message', :foreign_key => 'recipient_id'
validates :username,
:presence => true,
:uniqueness => true,
:length => { :in => 3..20 }
validates :email,
:presence => true,
:uniqueness => true,
:format => EMAIL_REGEX
validates :password, :confirmation => true
validates_length_of :password, :in => 6..20, :on => :create
before_save :encrypt_password
after_save :clear_password
def encrypt_password
if !password.empty?
self.salt = BCrypt::Engine.generate_salt
self.encrypted_password= BCrypt::Engine.hash_secret(password, salt)
end
end
def clear_password
self.password = nil
end
def self.authenticate(username_or_email="", login_password="")
if EMAIL_REGEX.match(username_or_email)
user = User.find_by_email(username_or_email)
else
user = User.find_by_username(username_or_email)
end
if user && user.match_password(login_password)
return user
else
return false
end
end
def match_password(login_password="")
encrypted_password == BCrypt::Engine.hash_secret(login_password, salt)
end
end
class Message < ActiveRecord::Base
belongs_to :sender, :class_name => 'User'
belongs_to :recipient, :class_name => 'User'
end
end
这是我遇到问题的控制器,user_id 不是自动生成的,当窥探 post 并调用 @current_user.save 时,它返回 false,这让我认为我在用户模型上的验证失败,但我只是这样做不知道在哪里。
module Notepasser::Controllers
class Users < R '/users'
attr_reader :current_user
#new user
def post
username ||= @input.username
password ||= @input.password
name ||= @input.name
github ||= @input.github_login
@current_user = Notepasser::Models::User.new(username: username,
password: password,
name: name,
github_login: github)
@current_user ? @status = 200 : @status = 400
@current_user.save
@current_user.to_json
end
end
end