我是rails的新手,我让这个应用程序学习。
链接 - Magazine
所以问题是,当用户创建/编辑他/她的文章并点击Back to all articles
时,用户就会被注销。在普通的Show页面上不会发生这种情况。我在创建和更新current_user
为nil
的方法中使用binding.pry进行了检查。知道发生了什么吗?
class SessionsController < ApplicationController
def create
user = User.from_omniauth(env["omniauth.auth"])
session[:user_id] = user.id
redirect_to root_path
end
def destroy
session[:user_id] = nil
redirect_to root_path
end
端
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
helper_method :current_user, :current_user_json
def current_user
@current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def current_user_json
user = current_user
if user
result = Jbuilder.new
result.name user.name
result.id user.id
result.target!
else
user.to_json
end
end
def user_access
redirect_to articles_path if current_user.blank?
end
end
def update
@article = Article.find(params[:article].delete(:id)) rescue nil
if @article.present? && @article.update_attributes(params[:article])
render json: {server_message: "Successfully updated Article."}
elsif @article.present?
render json: {server_message: "Article could not be updated."}
else
render json: {server_message: "Article not found."}
end
end
def create
article = Article.new(params[:article])
article.save ? response = {server_message: "Successfully created Article."} : response = {server_message: "Article not created, please try again."}
render json: response
end
Magazine::Application.routes.draw do
get "sessions/create"
get "sessions/destroy"
root :to => 'articles#index'
resources :articles do
resources :comments
end
resources :comments do
resources :comments
end
get 'auth/:provider/callback', to: 'sessions#create'
get 'auth/failure', to: redirect('/')
get 'signout', to: 'sessions#destroy', as: 'signout'
resources :sessions, only: [:create, :destroy]
end
$http({
method: 'POST',
url: '/articles',
data: {article: $scope.articleForm}
}).success(function(response) {
alert(response.server_message);
$scope.articleForm = angular.copy(articleForm);
}).error(function(response){
alert(response.server_message);
});
$http({
method: 'PUT',
url: '/articles/'+$scope.single_article.id,
data: {article: $scope.articleForm}
}).success(function(response) {
alert(response.server_message);
}).error(function(response){
alert(response.server_message);
});
答案 0 :(得分:1)
您的日志中有什么以及您的网页模板是什么样的?
当您从JavaScript执行表单提交时,它似乎没有获取表单身份验证令牌。没有它这一行
protect_from_forgery with: :exception
使得除了GET之外的任何不提供当前身份验证令牌的请求都会引发异常并丢弃会话。后者可能是用户在访问其他页面时退出的原因。
要弄清楚是否是这种情况,请尝试删除此行并查看问题是否重现。