Ruby 如何为模型中的where条件编写范围
我有下面的型号Ruby 如何为模型中的where条件编写范围,ruby,ruby-on-rails-4,Ruby,Ruby On Rails 4,我有下面的型号 class Customer class CustomerUsage < ActiveRecord::Base self.table_name = 'vCustomerDetails' end end class客户 类CustomerSage
class Customer
class CustomerUsage < ActiveRecord::Base
self.table_name = 'vCustomerDetails'
end
end
class客户
类CustomerSage
如何为
编写范围,其中vCustomerDetails.State='California'和vCustomerDetails.Statusflag='Y'
?与下面的内容不完全一样,但应该是这样的
scope :customers_from_california, -> { where(state: "California") }
scope :having_status_flag, -> { where(flag: "Y") }
你也可以像这样加入他们
scope :flagged_californians, ->{customers_from_california.where(flag: "Y")}
p、 我知道命名很糟糕-)我不确定这是否有效。OP似乎使用大写列名。@spickermann取决于使用的适配器和/或数据库本身。我知道
sql server
适配器有一个reflect\u lowercase\u schema
选项,该选项得到了适当的处理(对于方法命名,例如当设置为true
时,`def State`变为def State
)。至于我知道ms sql不关心的数据库,mySQL有一个启用/禁用的选项,这个功能,我还没有遇到过postgresql关心的时候(因为我没有使用过它们,所以不能代表任何其他数据库)@marmeladze可能会将名称更改为:flagged_californians
:)是的,那更好-)@spickermann我刚刚演示了它应该如何编写,并假设问题所有者知道他/她将如何修复它以正确的方式工作。为什么不遵循Rails惯例?使用大写的表名和列名不允许使用Rails的魔力,这会使一切变得更加困难。