1

我正在尝试为 Rails 应用程序中的所有模型定义一个 named_scope。

目前,我已经能够通过为 ActiveRecord::Base 编写一个初始化程序并将常规方法放入其中来接近这一点。当然,这在创建查询链时并没有提供真正的优势,并且可能是完成工作的最简单的方式。

但是,当我开始尝试使用 has_many、named_scope 等... ActiveRecord 方法时,它不起作用。

虽然我知道我的 named_scope 可能不正确,但我真的只想帮助定义 named_scope。另外,我目前对任何 Ruby ACL GEM 都不感兴趣。

在初始化器/中:

class ActiveRecord::Base

  has_many(:permissions)
  named_scope(:acl_check, lambda do |user_id, method|
        {
            :include => :permission,
            :conditions => [
                ["permissions.user_id=?", user_id],
                ["permissions.method=?", method],
                ["permissions.classname=?", self.class.name]
            ]
        }
  end)

    # Conducts a permission check for the current instance.
    def check_acl?(user_id, method)

        # Perform the permission check by User.
        permission_check = Permission.find_by_user_id_and_instance_id_and_classname_and_method(user_id, self.id, self.class.name, method)
        if(permission_check)
            # If the row exists, we generate a hit.
            return(true)
        end

        # Perform the permission check by Role.

        # Otherwise, the permissions check was a miss.
        return(false)

    end

end
4

1 回答 1

1

has_many可能不起作用,因为它是在类主体中评估的,并且预期的外键是用于评估它的类而不是继承类。(例如 id=42 的 Blog 模型可以有许多以 blog_id = 42 存储的 Comment 模型,使其工作所需的键基于类名)

如果命名范围是正确的,它应该可以工作。

继承的方法应该可以工作。

于 2009-06-25T18:31:17.720 回答