Ruby 别名属性与读取属性和写入属性
我正在使用没有rails的ActiveRecord。除了我正在写的一些辅助方法有一个奇怪的怪癖,我希望有人能解释一下。我有一个遗留数据库的模型。有些列名称中有一个“#”,所以我在模型中使用read_属性和write_属性定义了它们。例如(准确的示例但简化):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编号定
类产品
如果我用_别名调用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