我正在尝试使用rails教程,并遇到了问题。 在调试它的过程中,我遇到了这种奇怪的行为,我认为这与我的问题有关。
>rails console
DL is deprecated, please use Fiddle
Loading development environment (Rails 3.2.16)
irb(main):001:0> app.cookies['foo'] = 'bar'
=> "bar"
irb(main):002:0> app.cookies['remember_token'] = 'foobar'
=> "foobar"
irb(main):003:0> app.cookies['foo']
=> "bar"
irb(main):004:0> app.cookies['remember_token']
=> "foobar"
irb(main):005:0> app.put app.root_url
User Load (1.0ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" IS NULL LIMIT 1
CACHE (0.0ms) SELECT "users".* FROM "users" WHERE "users"."remember_token" IS NULL LIMIT 1
=> 200
irb(main):006:0> app.cookies['foo']
=> "bar"
irb(main):007:0> app.cookies['remember_token']
=> ""
注意在放置后cookie ['foo']如何设置为'bar',但cookies ['remember_token']设置为“”
任何人都可以解释这里可能发生的事情吗? 我在模型中有一个“remember_token”列,但我不知道它应该如何发挥作用。
以下是模型:
class User < ActiveRecord::Base
attr_accessible :email, :name, :password, :password_confirmation
has_secure_password
validates :name, presence: true,
length: { maximum: 50 }
VALID_EMAIL_REGEX = /\A[\w+\-.]+@[a-z\d\-.]+\.[a-z]+\z/i
validates :email, presence: true,
format: { with: VALID_EMAIL_REGEX },
uniqueness: { case_sensitive: false }
validates :password, presence: true,
length: { minimum: 6 }
validates :password_confirmation, presence: true
before_save { email.downcase! }
before_save :create_remember_token
private
def create_remember_token
puts "in create remember_token" #added for debug
self.remember_token = SecureRandom.urlsafe_base64
puts remember_token #added for debug
end
end
这是数据库:
ActiveRecord::Schema.define(:version => 20140111165943) do
create_table "users", :force => true do |t|
t.string "name"
t.string "email"
t.datetime "created_at", :null => false
t.datetime "updated_at", :null => false
t.string "password_digest"
t.string "remember_token"
end
add_index "users", ["email"], :name => "index_users_on_email", :unique => true
add_index "users", ["remember_token"], :name => "index_users_on_remember_token"
end
我原来的问题与测试失败有关,可以找到here
更新:找到这种奇怪行为的来源
当我开始聚集代码以显示完整的控制器时(根据评论中的要求),很明显这将成为我问题的根源。
class ApplicationController < ActionController::Base
protect_from_forgery
include SessionsHelper
# Force signout to prevent CSRF attacks
def handle_unverified_request
sign_out
super
end
end
这里是sign_out方法(在我的sessions_helper中)
def sign_out
puts "in sign out"
cookies.delete :remember_token
self.current_user = nil
end
我在sign_out方法中添加了一个put,并且看到它只是在执行put(但不是get)时被调用。现在我必须回到教程,看看我一定做错了什么。
答案 0 :(得分:0)
这里的问题是在handle_unverified_request中使用了protect_from_forgery和sign_out方法的结果。 有关详细信息,请参阅问题末尾的更新