Christian-G
Christian-G

Reputation: 2361

'case' inside of where clause

I have the following class method, and was wondering if there is an prettier (more ruby-ist) way of going about this.

def self.of_users_that(type)
  case type 
  when "registered"
    type = 1
  when "apologized"
    type = 2
  end
  Subscription.where(:regoption_id => type)
end

Thanks!

Upvotes: 0

Views: 60

Answers (2)

jvnill
jvnill

Reputation: 29599

I usually declare a constant inside the model for these kinds of constants. So same answer as Sergio, but using the constant

class Subscription < ActiveRecord::Base
  USER_TYPES = { 'registered' => 1, 'apologized' => 2 }

  def self.of_users_that(type)
    where(regoption_id: USER_TYPES[type])
  end
end

or just use scopes

scope :registered, where(regoption_id: 1)
scope :apologized, where(regoption_id: 2)

or combination

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

Upvotes: 1

Sergio Tulentsev
Sergio Tulentsev

Reputation: 230481

It's considered bad taste (a code smell) to redefine variables like that (transform it from string to integer).

Here's a cleaner version of your code:

def self.of_users_that(type)
  map = {'registered' => 1, 
         'apologized' => 2}
  Subscription.where(:regoption_id => map[type])
end

Upvotes: 2

Related Questions