调用Ruby的方法

时间:2013-05-27 07:32:24

标签: ruby-on-rails ruby scope

我在CanCan gem中为rails找到了这段代码:

def initialize(user)
    can do |action, subject_class, subject|
      user.permissions.find_all_by_action(aliases_for_action(action)).any? do |permission|
        permission.subject_class == subject_class.to_s &&
          (subject.nil? || permission.subject_id.nil? || permission.subject_id == subject.id)
      end
    end
  end

我知道可以多次调用该方法,但参数如何传递?变量actionsubject_classsubject在哪里发起?

1 个答案:

答案 0 :(得分:0)

根据cancan wiki中给出的示例,有以下模型:

class User < ActiveRecord::Base
  has_many :permissions
end

class Permissions < ActiveRecord::Base
  belongs_to :user
end

actionsubject_classsubject_idpermissions表格和数据库中数据库中的列。 permission模型为ActiveRecord自动生成模型对象的方法。所以例如

@permission = Permission.new
@permission.action = :new
@permission.subject_class = :ApplicationController
@permission.save

这会将此数据保存在权限表

此外,

  • action =索引,编辑,删除等具体操作。
  • subject_class =是控制器的名称,如ApplicationController
  • subject_id =可选