ruby-on-rails - 未定义的方法 `admin?' 为 nil :NilClass

标签 ruby-on-rails ruby-on-rails-3 authentication authorization railscasts

我关注了 railscast #250 Authentication from Scratch 并且一切正常。现在我试图只在我的索引页面上显示编辑和销毁链接到管理员用户的。

我已经使用管理员 bool 字段设置了 mu 用户数据库,并尝试在另一个模型(远足径)的 View 中放置一个简单的 if 语句,以仅显示指向管理员用户的某些链接,但是在我尝试时出现此错误,undefined method 'admin?' for nil:NilClass
数据库架构

  create_table "users", :force => true do |t|
    t.string   "email"
    t.string   "password_digest"
    t.boolean  "admin"
    t.datetime "created_at",      :null => false
    t.datetime "updated_at",      :null => false
  end

用户模型
class User < ActiveRecord::Base
  attr_accessible :email, :password, :password_confirmation#, :admin

  validates :email, :uniqueness => true

  has_secure_password
end

应用 Controller
class ApplicationController < ActionController::Base
  protect_from_forgery

  # fetch the currently logged-in user record to see if the user is currently logged in
  # putting this method in ApplicationController so that it’s available in all controllers
  private
  def current_user
    # checks for a User based on the session’s user id that was stored when they logged in, and stores result in an instance variable
    @current_user ||= User.find(session[:user_id]) if session[:user_id]
  end
  # to give access to this method from all the views, the helper_method makes it a helper method
  helper_method :current_user

  # basic authorization, user must be logged in!
  def authorize
    redirect_to login_url, alert: "You must be logged in to perform this action" if current_user.nil?
  end
end

意见/远足径/index.html.erb
  <% if current_user.admin? %>
    <%= link_to t('.edit', :default => t("helpers.links.edit")),
              edit_hikingtrail_path(hikingtrail), :class => 'btn btn-mini' %>
    <%= link_to t('.destroy', :default => t("helpers.links.destroy")),
              hikingtrail_path(hikingtrail),
              :method => :delete,
              :data => { :confirm => t('.confirm', :default => t("helpers.links.confirm", :default => 'Are you sure?')) },
              :class => 'btn btn-mini btn-danger' %>
  <% end %>

最佳答案

current_user如果用户未根据您的代码登录,则为零。所以你需要这样做:

<% if current_user && current_user.admin? %>

或使用 try Rails 添加到所有对象的方法。
<% if current_user.try(:admin?) %>

关于ruby-on-rails - 未定义的方法 `admin?' 为 nil :NilClass,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15855138/

相关文章:

ruby-on-rails - 如何比较 Float 和 Nil 以返回有效答案?

ruby-on-rails-3 - 如何将 Prawn PDF 文件存储到 Amazon S3 中

javascript - BigQuery 与 "signed urls"的相似度

ruby-on-rails - 随机搜索结果

ruby-on-rails - 添加评论 + Ajax

ruby-on-rails - 如何将时区全名翻译成 tz 缩写?

PHP:我的第一个登录系统不会验证密码

node.js - 将 auth0 集成到 web 应用程序 express/node js 中

ruby-on-rails - 错误 rbenv : 2. 1.2 未安装或未找到

mysql - 根据关联模型中的值对记录进行排序