【问题标题】:NoMethodError in Articles#index undefined method `is_admin' for nil:NilClassArticles#index 中的 NoMethodError 未定义方法 `is_admin' for nil:NilClass
【发布时间】:2013-04-05 03:35:10
【问题描述】:

我正在尝试在视图中实现一些条件,例如“编辑”和“删除”按钮,只有当当前用户是我的应用程序的管理员时才应该可见。当我在我的文章/index.html.erb 页面中尝试 时,我得到未定义的方法“is_admin”错误。

我不能在文章索引页面中使用 current_user 设计方法来获取用户吗?请建议我如何获取用户,然后检查用户是否为管理员。

我的代码文件如下:

articles/index.html.erb

<%- model_class = Article -%>
<div class="">
  <h1><%=t '.title', :default => model_class.model_name.human.pluralize %></h1>
</div>

<div style="border: 1px solid #1763A4;border-radius: 4px 4px 4px 4px;margin: 0 0 20px; padding: 20px 20px 10px;">

    <% @articles.each do |article| %>
    <div style="border: 1px solid #51702E;border-radius: 4px 4px 4px 4px;margin: 0 0 20px; padding: 20px 20px 10px;">
       <div style="color:#51702E"><h2><%= article.title %></h2></div>
       <div style="color:#666666"> <%= article.created_at %></div> 
       <% if current_user.is_admin %> 
       <div> <%= truncate(article.body, :length => 500, :separator => ' ') %></div>  
     <%= link_to "edit",edit_article_path(article), :class => 'btn btn-warning btn' %>
     <%= link_to "delete",article_path(article),:method => :delete,:confirm => 'Are you sure?',:class => 'btn  btn-danger' %>
     <% end %>
     <%= link_to "VIEW MORE...",article_path(article), :class => 'btn btn-primary' %> 
     </li>
     </div>
    <% end %>
<%= link_to "Create new Article", new_article_path, :class => 'btn btn-large btn-primary' %>

articles_controller.rb

class ArticlesController < ApplicationController
    def index
        @articles = Article.all
    end

    def show
      @article = Article.find(params[:id])
    end

    def new
      @article = Article.new
    end

    def create
      @article = Article.new(params[:article])

      @article.save
      redirect_to article_path(@article)
    end

    def destroy
      @article = Article.find(params[:id])
      @article.destroy
      redirect_to action:  'index'  
    end

    def edit
      @article = Article.find(params[:id])
    end

    def update
      @article = Article.find(params[:id])
      @article.update_attributes(params[:article])
      flash.notice = "Article '#{@article.title}' Updated!"
      redirect_to article_path(@article)
     end
end

模型:article.rb

class Article < ActiveRecord::Base
   attr_accessible :title, :body
   has_many :comments
   belongs_to :user
end

用户.rb

class User < ActiveRecord::Base
    has_many :articles
    has_many :comments
  # Include default devise modules. Others available are:
  # :token_authenticatable, :confirmable,
  # :lockable, :timeoutable and :omniauthable
  devise :database_authenticatable, :registerable,
         :recoverable, :rememberable, :trackable, :validatable

  # Setup accessible (or protected) attributes for your model
  attr_accessible :username, :email, :password, :password_confirmation, :remember_me
   attr_accessible :title, :body
end

用户表

 create_table "users", :force => true do |t|
    t.string   "email",                  :default => "", :null => false
    t.string   "encrypted_password",     :default => "", :null => false
    t.string   "reset_password_token"
    t.datetime "reset_password_sent_at"
    t.datetime "remember_created_at"
    t.integer  "sign_in_count",          :default => 0
    t.datetime "current_sign_in_at"
    t.datetime "last_sign_in_at"
    t.string   "current_sign_in_ip"
    t.string   "last_sign_in_ip"
    t.boolean  "is_admin"
    t.boolean  "is_active"
    t.datetime "created_at",                             :null => false
    t.datetime "updated_at",                             :null => false
    t.string   "username"
  end

【问题讨论】:

    标签: ruby-on-rails ruby devise admin


    【解决方案1】:

    来自https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role

    如果页面可能没有设置 current_user 则:

    if current_user.try(:admin?)
      # do something
    end
    

    或者你的情况

    if current_user.try(:is_admin)
      # do something
    end
    

    当没有当前用户(即未登录)时,这应该可以工作

    【讨论】:

    • 嗨烤饼,它对我有用,非常感谢,今天你救了我:) 但我不明白为什么它有效,而不是 current_user.is_admin。请你解释一下。跨度>
    • 正如我所说,用户可能没有登录。try函数只检查它左边的对象是否为nil,如果不是,括号中的函数将被调用,否则不会。跨度>
    • 嗨烤饼,我可以如何为您的声誉或徽章做出贡献?
    • @VSiingh 如果您愿意,可以单击左侧的复选标记以接受答案。此外,您可以通过单击答案旁边的向上箭头来投票赞成答案。你绝对应该看看 about 部分:stackoverflow.com/about
    【解决方案2】:

    您的 User 模型是否有 admin 属性?

    如果你不需要定义一个,例如

    class AddAdminToUsers < ActiveRecord::Migration
      def self.up
        add_column :users, :admin, :boolean, :default => false
      end
    
     def self.down
       remove_column :users, :admin
     end
    end
    

    然后运行 ​​rake db:migrate

    然后您应该能够通过调用来检查用户是否是管理员:

    current_user.admin?
    

    在设计中还有其他选项可以做到这一点,在这里查看它们

    https://github.com/plataformatec/devise/wiki/How-To:-Add-an-Admin-role

    【讨论】:

    • 嗨,是的,用户表的 is_admin 列是布尔值。我试图“current_user.is_admin”,但它拒绝 current_user 的实例。
    • 嗨,用户表已经有 is_admin 列,我已经在其他页面上使用过,例如
    猜你喜欢
    • 1970-01-01
    • 2021-11-05
    • 2012-08-31
    • 2013-04-24
    • 2013-04-25
    • 1970-01-01
    • 2015-07-19
    • 2013-11-14
    • 2013-01-14
    相关资源
    最近更新 更多