模块可以向 Rails 模型添加关系和 named_scopes [英] Can modules add relationships and named_scopes to Rails models

查看:36
本文介绍了模块可以向 Rails 模型添加关系和 named_scopes的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何创建一个模块,当包含在模型中时,它会自动添加一些关系和 named_scopes?

How do I create a module that when included in a model will automatically add some relationships and named_scopes?

这是我现在所拥有的:

module Resource

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)

end

虽然我在尝试启动服务器时遇到以下错误:

Although I'm getting the following error when I try to start my server:

......config/initializers/Resources.rb:5: undefined method `named_scope' for Resource:Module (NoMethodError)

感谢所有回复的人!:)

Thanks to all who respond! :)

推荐答案

您想覆盖模块上的 includes() 或 extended() 方法,只要模块(出人意料地)被包含或扩展,就会调用该方法.像下面这样的事情应该做你想做的:

You want to override the included() or extended() method on the module, which is called whenever the Module is (surprisingly enough) included or extended. Something like the following should do what you want:

module Foo
  def self.extended (base)
    base.class_eval do
      has_many :doodads
    end
  end
end

为了清楚起见,这稍微简化了一点,但您应该能够从原始示例中添加所有命名范围等.

That's simplified a bit for clarity, but you should be able to add all the named scopes, etc, from your original example.

这篇关于模块可以向 Rails 模型添加关系和 named_scopes的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆