我有一个接受 json 请求以创建用户的 rails 应用程序。一个注册基本上是一个 GET。当我传入这个 url 时,我无法创建用户http://localhost:3000/sign_up.json?username=chalam&email=holy@yahoo.com&name=chalami&password=chalami
我知道我正在公开传递密码,但这不是我关心的问题。我检查了日志,这就是我所看到的
Started GET "/sign_up.json?username=chalam&email=holy@yahoo.com&name=chalami&password=[FILTERED]" for 127.0.0.1 at 2013-05-28 10:37:37 +0700
Processing by UsersController#create as JSON
Parameters: {"username"=>"chalam", "email"=>"holy@yahoo.com", "name"=>"chalami", "password"=>"[FILTERED]"}
(0.1ms) begin transaction
User Exists (0.1ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1
User Exists (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
(0.0ms) rollback transaction
(0.0ms) begin transaction
CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1
CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
(0.0ms) rollback transaction
Completed 200 OK in 6ms (Views: 0.1ms | ActiveRecord: 0.3ms)
如您所见,尽管参数Parameters: {"username"=>"chalam", "email"=>"holy@yahoo.com", "name"=>"chalami", "password"=>"[FILTERED]"}
清楚地表明正在传递参数,但它们没有被输入数据库CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."username" IS NULL LIMIT 1
CACHE (0.0ms) SELECT 1 AS one FROM "users" WHERE "users"."email" IS NULL LIMIT 1
主要问题是参数中的数据没有被“用于”创建用户
需要注意的一件事是我可以通过终端中的控制台创建用户。我将尝试包含所有相关信息 rails version: 3.2.13 我使用的是 thin 而不是 WEBBRICK
我的用户.rb
class User < ActiveRecord::Base
attr_accessible :email, :name, :username
attr_accessor :password
before_save :encrypt_password
validates_uniqueness_of :username, :email
validates_presence_of :password, :on => :create
validates_presence_of :email, :username
def encrypt_password
if password.present?
self.password_salt = BCrypt::Engine.generate_salt
self.password_hash = BCrypt::Engine.hash_secret(password, password_salt)
end
end
def self.authenticate(username, password)
user = find_by_username(username)
if(user && user.password_hash == BCrypt::Engine.hash_secret(password, user.password_salt))
user
else
nil
end
end
end
我的控制器
class UsersController < ApplicationController
respond_to :json
def new
@user = User.new
end
def create
@user = User.new(params[:user])
@user.save
if @user.save
respond_to do |format|
format.json { render :json => {:status => "200", :message => "Signed up successfully"}}
end
else
respond_to do |format|
puts @user.errors.inspect
format.json { render :json => {:status => "400", :message => "Failed"}}
end
end
end
def index
@user = User.all
render :json =>@user
end
end