1

我正在尝试这样做:

类 NotesController < ApplicationController

定义索引

@user = User.find_by_authentication_token(params[:token])

@notes = @user.notes

...

但我收到一个错误:

Started POST "/api/login" for 10.0.0.4 at 2013-07-22 13:20:43 +0300
Processing by Api::LoginController#login as JSON
  Parameters: {"user"=>{"password"=>"[FILTERED]", "email"=>"pp@pp.pp"}, "login"=>{"user"=>{"password"=>"[FILTERED]", "email"=>"pp@pp.pp"}}}
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."email" = 'pp@pp.pp' LIMIT 1
  User Load (1.0ms)  SELECT "users".* FROM "users" WHERE "users"."authentication_token" = 'GFRWkkLCq3xQx5rTRTFp' LIMIT 1
Completed 200 OK in 119ms (Views: 0.0ms | ActiveRecord: 3.0ms)


Started GET "/notes?token=GFRWkkLCq3xQx5rTRTFp" for 10.0.0.4 at 2013-07-22 13:20:44 +0300
Processing by NotesController#index as JSON
  Parameters: {"token"=>"GFRWkkLCq3xQx5rTRTFp", "note"=>{}}
  User Load (0.0ms)  SELECT "users".* FROM "users" WHERE "users"."authentication_token" = 'GFRWkkLCq3xQx5rTRTFp' LIMIT 1
Completed 500 Internal Server Error in 1ms

NoMethodError (undefined method `notes' for nil:NilClass):
  app/controllers/notes_controller.rb:7:in `index'

如您所见,代码

User.find_by_authentication_token(params[:token])

一直返回零。

4

1 回答 1

0

想通了:问题是我忘记在方法user.ensure_authentication_token之后保存(提交)用户

def login
    user = User.find_for_database_authentication(:email => params[:user][:email])
    if user.nil?
      render :json => {:result => 'ERROR'}
    else
      if user.valid_password?(params[:user][:password])
        user.ensure_authentication_token
        user.save
        render :json => {:result => user.authentication_token}
于 2013-07-22T11:01:27.143 回答