【问题标题】:how to write a scope for where conditions in model如何为模型中的 where 条件编写范围
【发布时间】:2017-04-19 16:32:44
【问题描述】:

我有以下型号

class Customer
  class CustomerUsage < ActiveRecord::Base

    self.table_name = 'vCustomerDetails'

  end
end

如何为where vCustomerDetails.State = 'California' and vCustomerDetails.Statusflag = 'Y' 编写范围?

【问题讨论】:

  • 为什么不遵循 Rails 约定?使用大写的表名和列名不会让你使用 Rails 的魔力,而且会让一切变得更加困难。

标签: ruby ruby-on-rails-4


【解决方案1】:

不完全像下面,但应该像这样。

  scope :customers_from_california, -> { where(state: "California") }
  scope :having_status_flag, -> { where(flag: "Y") }

你也可以加入他们,

  scope :flagged_californians, ->{customers_from_california.where(flag: "Y")}

附言我知道命名很烂 -))

【讨论】:

  • 我不确定这是否可行。似乎 OP 使用大写的列名。
  • @spickermann 取决于使用的适配器和/或数据库本身。我知道sql-server 适配器有一个reflect_lowercase_schema 选项,该选项处理得当(对于方法命名,例如当设置为true 时,`def State` 变为def state)。至于我知道ms-sql不关心大小写的数据库,mysql有一个启用/禁用的选项,这个特性我还没有遇到过postgresql关心的时候(不能代表任何其他人,因为我没有' t 使用它们)。 @marmeladze 可能会将名称更改为 :flagged_californians :)
  • 是的,这样更好 -))
  • @spickermann 我刚刚展示了它应该如何编写,并假设问题所有者知道他/她将如何修复它以使其正常工作。
猜你喜欢
  • 1970-01-01
  • 2017-12-14
  • 1970-01-01
  • 2020-02-08
  • 2016-08-23
  • 2023-03-18
  • 2017-05-07
  • 1970-01-01
  • 2021-12-02
相关资源
最近更新 更多