Ruby On Rails:CanCan with Devise error&#39; undefined method`find_by_name&#39;对于#<role:0x304ad18> </role:0x304ad18>

时间:2012-11-27 13:50:34

标签: mysql ruby-on-rails-3 devise cancan

我对cancan非常困惑,我试图从我的mysql数据库中获取cancan的角色。我使用的控制器没有像show / edit / destroy那样的动作(我认为它被称为非RESTful控制器?)。 我在我的用户表中有一个Role_id列,在我的角色表中有一个id和rolename。

我得到的只是这个错误:

未定义的方法`find_by_name&#39;对于#

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

这是我的User.rb:

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

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

  validates_uniqueness_of :username
  belongs_to :role

def role?(role)
    return !!self.role.find_by_name(role.to_s.camelize)
end
end

Role.rb:

class Role < ActiveRecord::Base
  has_many :users
  attr_accessible :users, :name 
end

我在这里工作的控制器是:

class WsdlController < ApplicationController
 authorize_resource :class => false
    $liga_id = 456
    $liga_short = "bl1"
    $saison = 2012

    def connect
        @client = Savon::Client.new("http://www.openligadb.de/Webservices/Sportsdata.asmx?WSDL")
        @output = ""
    end

    def get_all_for_new_saison
        if @client.nil?
            connect
        end
        #get_teams_by_league_saison
        #get_matchdata_by_league_saison
    end 
end

1 个答案:

答案 0 :(得分:0)

find_by_nameActiveRecord 类方法。 (请参阅Active Record Query Interface指南)您正在调用它,就像实例方法一样。

尝试更改此内容:

def role?(role)
    return !!self.role.find_by_name(role.to_s.camelize)
end

这样的事情:

def role?(role_name)
    return self.role.present? && self.role.name == role_name.to_s
end

当然,在ruby中,returnself都是可选的。