更新
问题解决了
我只需将protect_from_forgery
放在Users
控制器中。谢谢大家。
Rails 4.0.2
当我尝试在users
表中创建新记录时,我在浏览器中收到此消息:
ActionController::InvalidAuthenticityToken in UsersController#create
ActionController::InvalidAuthenticityToken
但它发生在Chrome(32.0.1700.107)和Opera(12.16)浏览器中。在Firefox(27.0.1)和IE 10.0.13中一切正常。也许没关系,但我不得不说我也使用has_secure_password(bcrypt_ruby)。
Rails日志:
...
Started POST "/users" for 127.0.0.1 at 2014-02-19 10:26:05 +0400
Processing by UsersController#create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"93jpgxCSY3XzZkIJKraOodyObBoaPoPMVz3RiOVBL10=", "user"=>{"name"=>"", "surname"=>"", "patronymic"=>"", "email"=>"", "address"=>"", "phone"=>"", "phone2"=>"", "password"=>"[FILTERED]", "password_confirmation"=>"[FILTERED]"}, "commit"=>"Создать пользователя"}
Can't verify CSRF token authenticity
Completed 422 Unprocessable Entity in 2ms
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
actionpack (4.0.2) lib/action_controller/metal/request_forgery_protection.rb:163:in `handle_unverified_request'
actionpack (4.0.2) lib/action_controller/metal/request_forgery_protection.rb:170:in `handle_unverified_request'
actionpack (4.0.2) lib/action_controller/metal/request_forgery_protection.rb:177:in `verify_authenticity_token'
...
查看文件users/new.html.slim
:
= stylesheet_link_tag 'users'
.new_user_container
= form_for @user do |f|
= f.label "Имя"
br
= f.text_field :name
br
= f.label "Фамилия"
br
= f.text_field :surname
br
= f.label "Отчество"
br
= f.text_field :patronymic
br
= f.label "Пароль"
br
= f.text_field :password
br
= f.label "Подтверждение пароля"
br
= f.text_field :password_confirmation
br
br
= f.submit "Создать пользователя"
答案 0 :(得分:6)
我只需将protect_from_forgery
放在Users控制器中。谢谢大家。
class UsersController < ApplicationController
protect_from_forgery
def index
#@users = User.all.includes(:roles)
@users = User.all
end
def show
end
def new
@user = User.new
end
def create
@user = User.new user_params
puts @user.errors.inspect
if @user.save
flash[:notice] = "Пользователь удачно создан"
redirect_to :users
else
flash[:notice] = "Пользователь не создан"
render file: :'users/user_error'
end
flash["notice"] = "Test notice"
#redirect_to :users
end
end
答案 1 :(得分:1)
我遇到了同样的问题。这只发生在Chrome浏览器中。但我的问题在于我禁止在Chrome的Content Settings
中使用Cookie。所以只需启用它,或者如果你必须禁止它,请选择Clear on quit
。
注意:此设置来自我的另一台设备上的Chrome浏览器。如果您使用自己的Google帐户登录Chrome,则Chrome会在设备之间同步您的设置。所以可能很难意识到这个问题。
希望这可以帮助其他遇到此问题的人。