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
2
  • You can directly call .where method on model. Why again you are defining a method for it? Commented Sep 19, 2017 at 12:40
  • @user2950593 if the answer was fine, you can close this question by choosing it. If you have any further doubt, please comment Commented Oct 10, 2017 at 11:08

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

7 Comments

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
Or def self.find_something(param)
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 - 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.
this pretty outdated answer provides a good overview 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
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.