1

I've been through railscast 270 and implemented a basic sign up form for users (in this app called players). The forms work fine, but when I try and authenticate over json, I get errors. Any ideas on how to fix this?

POST request to http://localhost:3000/players with body:

{
  "email": "aaaa@baaab.com",
  "username": "jaaaack",
  "password": "abc123",
  "password_confirmation": "abc123"
}

displays errors:

<h2>Form is invalid</h2>
<ul>
  <li>Password digest can't be blank</li>
  <li>Password can't be blank</li>
</ul>

players_controller.rb

class PlayersController < ApplicationController
  def new  
    @player = Player.new  
  end  

  def create  
    @player = Player.new(params[:player])  
    if @player.save  
      redirect_to root_url, :notice => "Signed up!"  
    else  
      render "new"  
    end  
  end
end

player.rb

class Player < ActiveRecord::Base
  attr_accessible :username, :email, :password, :password_confirmation  

  has_secure_password
  validates_presence_of :password, :on => :create
  validates_presence_of :email
  validates_presence_of :username
  validates_uniqueness_of :email
  validates_uniqueness_of :username
end

routes.rb

get "sign_up" => "players#new", :as => "sign_up"    
resources :players, :only => [:create]
root :to => 'home#index'
4

1 回答 1

3

I think your problem is being caused by your json not being quite right (and the way rails interprets it by default).

If you inspect your log file (log/development.log) you'll see something like the following (allbeit with fewer line breaks):

Processing by PlayersController#create as HTML
Parameters: {
  "email"=>"aaaa@baaab.com", 
  "username"=>"jaaaack", 
  "password"=>"[FILTERED]", 
  "password_confirmation"=>"[FILTERED]", 
  "players"=>{
    "email"=>"aaaa@baaab.com", 
    "username"=>"jaaaack", 
    "password"=>"[FILTERED]",
    "password_confirmation"=>"[FILTERED]"
  },
  "controller" => "players",
  "action" => "create"
}

As you can see the json data is included twice - once in the root of the params hash, and again as the value for a key in params, using (I think) the controller name as the key.

Thus, given that you've got attr_accessible setup properly for you could do one of the following in PlayersController#create:

@player = Player.new(params[:players]) 

OR

@player = Player.new(params)

Obviously this would hamper your use of the same action in the controller for handling data from a HTML form submission. To get around this you could wrap the JSON as follows:

{ "player":
  {
    "email": "aaaa@baaab.com",
    "username": "jaaaack",
    "password": "abc123",
    "password_confirmation": "abc123"
  }
}

Which will make params[:player] have the right information in it in order to create your new record using your existing code

于 2012-01-22T16:13:12.937 回答