【发布时间】:2014-10-28 07:47:15
【问题描述】:
我想创建一个 Current_User 方法,但我不想使用 gem 或类似方法。我将如何在 Rails 4.1.2 中做到这一点
Questions_Controller 我想要 current_user 方法的地方。
class QuestionsController < ApplicationController
before_filter :auth, only: [:create, :your_questions, :edit, :update]
# def index
# @question = Question.new
# @questions = Question.unsolved(params)
# end
@questions = current_user.your_questions(params[:page])
def your_questions(page)
questions.paginate(page: page, order: 'created_at DESC', per_page: 3)
end
def self.unsolved(params)
order('created_at DESC').where(solved: false).paginate(page: params[:page],per_page: 3)
end
def create
@question = current_user.questions.build(params[:question])
if @question.save
flash[:success] = 'Your question has been posted!'
redirect_to @question
else
@questions = Question.unsolved(params)
render 'index'
end
end
def new
@question = Question.new
end
def show
# raise FOO
puts params
@question = Question.find(params[:id])
@answer = Answer.new
end
def your_questions
@questions = current_user.your_questions(params[:page])
# current_user.your_questions(params[:id])
end
def edit
@question = current_user.questions.find(params[:id])
end
def update
@question = current_user.questions.find(params[:id])
if @question.update_attributes(params[:question])
flash[:success] = 'Your question has been updated!'
redirect_to @question
else
render 'edit'
end
end
def search
@questions = Question.search(params)
end
end
我的用户模型
class User < ActiveRecord::Base
has_many :questions
has_many :answers
# attr_accessible :username, :password, :password_confirmation
has_secure_password
# validates :username, presence: true, uniqueness: { case_sensitive: false },
# length: { in: 4..12 },
# format: { with: /A[a-z][a-z0-9]*z/, message: 'can only contain lowercase letters and numbers' }
validates :password, length: { in: 4..8 }
validates :password_confirmation, length: { in: 4..8 }
def your_questions(page)
questions.paginate(page: page, order: 'created_at DESC', per_page: 3)
end
end
我的应用程序控制器
class ApplicationController < ActionController::Base
protect_from_forgery with: :exception
# protect_from_forgery
helper_method [:current_user, :logged_in?]
protected
private
def login(user)
session[:user_id] = user.id
end
def current_user
current_user ||= User.find(session[:user_id]) if session[:user_id]
end
def logged_in?
!current_user.nil?
end
def auth
redirect_to login_url, alert: 'You must login to access that page' unless logged_in?
end
end
如果您希望我将更多文件添加到问题中,请评论我是 Rails 开发人员的新手 ruby :)
【问题讨论】:
-
Michael Hartl's Rails Tutorial 查看第 8 章的
sign-in、sign-out和会话管理。这会让你朝着正确的方向前进。
标签: ruby-on-rails ruby