在Rails 3中具有继承关系的命名作用域映射到错误的表 [英] Named scopes with inheritance in Rails 3 mapping to wrong table

查看:70
本文介绍了在Rails 3中具有继承关系的命名作用域映射到错误的表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用具有命名作用域的类的继承:

I am attempting to use inheritance from a class which has a named scope:

Class A < ActiveRecord::Base
    scope :useful_scope, lambda { |value1, value2|
        where(:value1 => value1, :value2 => value2)
    end
end

Class B < A
    set_table_name "b"
end

我遇到的问题是sql查询中的表名仍然引用A类表:

The problem I'm encountering is that the table name in the sql queries still reference Class A's Table:

A.useful_scope("alpha", "beta").to_sql
 => "SELECT \"a\".* FROM \"a\" WHERE \"a\".\"value1\" = 'alpha' AND \"a\".\"value2\" = 'beta'"
B.useful_scope("alpha", "beta").to_sql
 => "SELECT \"b\".* FROM \"b\" WHERE \"a\".\"value1\" = 'alpha' AND \"a\".\"value2\" = 'beta'"

请注意,WHERE语句中的表名仍引用A.我正在修改一个现有的gem,它在整个A类范围内具有各种依赖性,因此我需要保持其当前语法.我想在WHERE子句SQL中维护表名称说明符,以确保在与其他命名作用域定义嵌套时作用域表现良好.

Note that the table names in the WHERE statement still refer to A. I am modifying an existing gem with various dependencies on the Class A scope throughout, so I need to maintain it's current syntax. I want to maintain the table name specifiers in the WHERE clause SQL to ensure that the scope will behave well when nested with other named scope definitions.

我尝试了以下操作:

  • 使用lambda参数作为表名.这破坏了其他仅提供当前2个属性的范围引用的语法.
  • 使用抽象类定义范围.表名的绑定相同,但使用的是Abstract Class的类名.
  • 使用在模块中定义的范围,包括该模块.表名的绑定相同.

有没有一种方法可以强制对每个继承的类进行作用域评估,以使它不会显式映射到父类表?

Is there a way that I can force the scope to be evaluated on each inherited class, so that it isn't explicitly mapped to the parent classes table?

推荐答案

我最终使用匿名作用域解决了此问题.代码如下:

I ended up using an anonymous scope to resolve this issue. The code looks like this:

def self.useful_scope(value1, value2)
  scoped(:conditions => { :value1 => value1, :value2 => value2 })
end

现在,它可以在父类和继承的类中正确评估,并保留范围的期望行为.

This now evaluates properly in both the parent and inherited classes, and retains the desired behavior of a scope.

这篇关于在Rails 3中具有继承关系的命名作用域映射到错误的表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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