Ruby 别名属性与读取属性和写入属性

Ruby 别名属性与读取属性和写入属性,ruby,activerecord,ruby-on-rails-4,rails-activerecord,Ruby,Activerecord,Ruby On Rails 4,Rails Activerecord,我正在使用没有rails的ActiveRecord。除了我正在写的一些辅助方法有一个奇怪的怪癖,我希望有人能解释一下。我有一个遗留数据库的模型。有些列名称中有一个“#”,所以我在模型中使用read_属性和write_属性定义了它们。例如(准确的示例但简化): 类产品5)一切正常 为什么ActiveRecord将pname正确地别名为name,而将sale正确地别名为sale\u number?错误是因为在where子句中使用了一个in EXISTIONS列。您还需要为sale到sale\u编号定

我正在使用没有rails的ActiveRecord。除了我正在写的一些辅助方法有一个奇怪的怪癖,我希望有人能解释一下。我有一个遗留数据库的模型。有些列名称中有一个“#”,所以我在模型中使用read_属性和write_属性定义了它们。例如(准确的示例但简化):

类产品
如果我用_别名调用
Product.helper _
,一切正常。但是,当我调用带有属性的
Product.helper\u时,我得到一个
ActiveRecord::StatementInvalid
错误,表示找不到列
sale\u number
。此外,如果我将
helper_中的代码替换为_属性
where('sale#'=>5)
一切正常


为什么ActiveRecord将
pname
正确地别名为
name
,而将
sale
正确地别名为
sale\u number

错误是因为在where子句中使用了一个in EXISTIONS列。您还需要为
sale
sale\u编号定义别名属性

在模型中,可以执行以下操作:

class Product < ActiveRecord::Base
  alias_attribute :sale_number, :"sale#"

  def self.helper_with_attribute
    where(sale_number: 5)
  end
end
类产品
使用此方法,您不需要仅为分配和检索目的定义setter和getter,因此可以删除
sale\u number
sale\u number=(value)
方法。使用
alias\u属性
,已使用别名

为什么ActiveRecord正确地将pname别名为name,但不正确 别名sale#到sale#号码

这是因为您已经定义了
alias\u attribute:name,:pname
,它提供了setter、getter和查询方法作为现有
pname
属性的别名。但是,对于
sale\u number
,您只定义了getter和setter,而没有定义查询方法

class Product < ActiveRecord::Base
  alias_attribute :sale_number, :"sale#"

  def self.helper_with_attribute
    where(sale_number: 5)
  end
end