Dave Sag
Dave Sag

Reputation: 13486

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?

Upvotes: 3

Views: 1675

Answers (1)

Geo
Geo

Reputation: 96827

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.

Upvotes: 2

Related Questions