Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using ActiveRecord's scope instruction to return a single result

I have the following class that works fine in my unit tests but I feel it could be simpler.

class License < ActiveRecord::Base
  scope :active, lambda {
    where("active_from <= ?", Date.today).order("version_number DESC")
  }
end

def current_license
  return License.active.first
end

public :current_license

I have tried appending the .first into the lambda clause but that causes an error.

How do I tell the scope I only want the first result, and thus eliminate the method current_license completely?

like image 327
Dave Sag Avatar asked Nov 20 '25 01:11

Dave Sag


1 Answers

Make it a method, and you can get this:

class License < ActiveRecord::Base

  def self.current_license
    return License.where("active_from <= ?", Date.today).order("version_number DESC").first
  end

end

As for the number of results, try to add a .limit(1). For more info, have a look here.

like image 73
Geo Avatar answered Nov 25 '25 00:11

Geo



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!