0

標準Userモデルがあり、adminブール値が含まれています。それをtrueに設定しているユーザーにとってはすべて問題ありませんが、通常のユーザーの場合、次のエラーが発生します。

undefined local variable or method `current_user'
app/models/doc.rb:18:in `mine'
app/controllers/docs_controller.rb:9:in `index'

Doc18 行目のモデルは次のようになります。

def self.mine
  where(:user_id => current_user.name, :retired => "active").order('created_at DESC')
end

私のUserモデルは次のようになります。

class User < ActiveRecord::Base
  devise :database_authenticatable, :registerable, :recoverable, :rememberable, :trackable, :validatable
  attr_accessor :current_password
  attr_accessible :name, :password, :password_confirmation, :current_password, :email, :remember_me, :admin
end

class Ability
  include CanCan::Ability
  def initialize(user)
    can :manage, :all if user.admin
  end
end

そして、アプリケーションコントローラーには次のものがあります。

class ApplicationController < ActionController::Base
  protect_from_forgery

  after_filter :user_activity

  rescue_from CanCan::AccessDenied do |exception|
    redirect_to root_path
  end

  def admin?
    self.admin == true
  end

  def authenticate_admin
    redirect_to :new_user_session_path unless current_user && current_user.admin?
  end

  private

  def user_activity
    current_user.try :touch
  end

end

それがすべて関連していると思います。私は一生これを理解することはできません。

4

1 に答える 1

1

ヘルパーは、current_userモデルからアクセスできないコントローラー メソッドです。現在のユーザーをパラメーターとしてコントローラーからモデルに渡す必要があります。

def self.mine(current_user)
  where(:user_id => current_user.name, :retired => "active").order('created_at DESC')
end

編集:サイドノート

user_idロジック内の文字列のようです。これがあなたがしていることである場合、あなたは再考する必要があります。データベース内の識別子を使用して、rails で belongs_to と has_many をセットアップすると、はるかに保守しやすくなります。文字列 ID の使用は型破りであり、非常に悪い場所で終わるうさぎの穴です。

于 2013-01-09T05:18:18.320 に答える