Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/52.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 扩展ActiveRecord别名以按方法查找_Ruby On Rails_Ruby_Activerecord - Fatal编程技术网

Ruby on rails 扩展ActiveRecord别名以按方法查找

Ruby on rails 扩展ActiveRecord别名以按方法查找,ruby-on-rails,ruby,activerecord,Ruby On Rails,Ruby,Activerecord,在ActiveRecord::Base子类中,我想为字段添加别名,因为在新类中有一个同名的等效字段。例如,我做了如下事情: class OldClass < ActiveRecord::Base alias_attribute :new_style_id, :id end class NewClass < ActiveRecord::Base ; end classoldclass

ActiveRecord::Base
子类中,我想为字段添加别名,因为在新类中有一个同名的等效字段。例如,我做了如下事情:

class OldClass < ActiveRecord::Base
  alias_attribute :new_style_id, :id
end
class NewClass < ActiveRecord::Base ; end
classoldclass

new\u-style\u-id
NewClass
上的一个字段,有一个类似于
find\u by\u-new\u-style\u-id
的查找器,但是
alias\u属性
不会为
OldClass
创建类似的查找,因此尝试调用
find\u by\u by\u-new\u-style\u-id
会在调用
OldClass>时引发未定义的方法异常。除了简单地将
find\u by\u new\u style\u id
添加到
OldClass
之外,还有没有一种方法可以让Rails自动生成别名的查找器,以便
OldClass
NewClass
都响应
find\u by\u new\u style\u id

您需要的是一个范围:

scope : find_by_new_style_id, -> (new_style_id){ where( 'style_id=?', new_style_id ) }
如果需要在多个类中使用它,可以使用关注点

module StyleScope
  extend ActiveSupport::Concern
  included do
    scope : find_by_new_style_id, -> (new_style_id){ where( 'style_id=?', new_style_id ) }
  end
end
在您的模型中:

ìnclude StyleScope

虽然这是一个解决方案,但我不确定它是否真的比我现在所做的更好,我现在所做的只是实现
find_by_new_style_id
def find_by_new_style_id(id));通过_id(id)查找_;在
OldClass
上结束
。您可以看看这篇文章: