我有以下类方法,并且想知道是否有更漂亮(更多ruby-ist)的方法来解决这个问题。
def self.of_users_that(type)
case type
when "registered"
type = 1
when "apologized"
type = 2
end
Subscription.where(:regoption_id => type)
end
谢谢!
答案 0 :(得分:2)
重新定义这样的变量(将它从字符串转换为整数)被认为是不好的味道(代码气味)。
以下是您的代码的更简洁版本:
def self.of_users_that(type)
map = {'registered' => 1,
'apologized' => 2}
Subscription.where(:regoption_id => map[type])
end
答案 1 :(得分:1)
我通常在模型中为这些常量声明一个常量。与塞尔吉奥一样的答案,但使用常数
class Subscription < ActiveRecord::Base
USER_TYPES = { 'registered' => 1, 'apologized' => 2 }
def self.of_users_that(type)
where(regoption_id: USER_TYPES[type])
end
end
或只使用范围
scope :registered, where(regoption_id: 1)
scope :apologized, where(regoption_id: 2)
或组合
class Subscription < ActiveRecord::Base
USER_TYPES = { 'registered' => 1, 'apologized' => 2 }
scope :registered, where(regoption_id: USER_TYPES['registered'])
scope :apologized, where(regoption_id: USER_TYPES['apologized'])
end