0

I have a ConversionRate model

class ConversionRate < ActiveRecord::Base
end

I want to move to model my controller method find_something

class ConversionRatesController < ActionController::Base
  #....
  def find_something (param)
    rate = ConversionRate.where(:param=> param)
  end
 end

How do I do this? I am thinking of something like this

class ConversionRate < ActiveRecord::Base
 def self.find_something(param)
   return self.where(:param=> param)
end
mabe02
  • 2,676
  • 2
  • 20
  • 35
user2950593
  • 9,233
  • 15
  • 67
  • 131

1 Answers1

2

It seems that you have already found your solution:

class ConversionRate < ActiveRecord::Base
 class << self
    def find_something(param)
     where(:param=> param)
    end
  end
end

An alternative could be to use a scope:

class ConversionRate < ActiveRecord::Base
  scope :find_something, ->(param) { where(param: param) }
end

Then you can call it from the controller like ConversionRate.find_something(params)

I would encourage the first approach if you need to perform some validation on your param, otherwise the second is very straightforward.

mabe02
  • 2,676
  • 2
  • 20
  • 35
  • Thanks! another quetion: how do I define method for instance of model? For example I have `cr= ConversionRate.new; cr.param = "123"; I want to write cr.find_another_param` – user2950593 Sep 19 '17 at 12:56
  • Or `def self.find_something(param)` – mahemoff Sep 19 '17 at 13:04
  • I guess that this is another question.. it would be a little confusing to add to the same answer. You can close this one and open another to keep the topic distinguished – mabe02 Sep 19 '17 at 13:11
  • @mabe02 - what's the advantage of the singleton method, rather than using a standard class method (i.e. @mahemoff's `def self.find_something `) or your scope? Asking out of curiosity.... not suggesting you're wrong or anything. – SRack Sep 19 '17 at 16:47
  • this pretty outdated answer provides a good overview https://stackoverflow.com/a/11816412/5687152 With `scope` you return a subset of an ActiveRecord::Relation, with a self.something method you can return what you prefer. I prefer to enclose class methods inside `class << self ; end` for clarity, but there is no difference with several `def self.something; end` – mabe02 Sep 20 '17 at 13:08
  • `class << self` can be useful if you want to group several class methods together. (I do find Ruby's `class <<` syntax conceptually weird and confusing though, just my opinion.) – mahemoff Sep 20 '17 at 13:28
  • @user2950593 can we consider your problem solved? In case, you can tick this answer – mabe02 Sep 20 '17 at 15:18