Question

Rails 3.2

How do you do find a range to last record in the console?

Distributor.find_by_id(2..last)

Thank you

Was it helpful?

Solution

You can simply do:

Distributor.where('id >= 2')

This also works, but it performs 2 queries:

Distributor.where(id: 2..Distributor.last.id)

OTHER TIPS

last(limit = nil)

Find the last record (or last N records if a parameter is supplied). If no order is defined it will order by primary key.

Person.last # returns the last object fetched by SELECT * FROM people
Person.where(["user_name = ?", user_name]).last
Person.order("created_on DESC").offset(5).last
Person.last(3) # returns the last three objects fetched by SELECT * FROM people.

http://api.rubyonrails.org/classes/ActiveRecord/FinderMethods.html

    def last(limit = nil)
      if limit
        if order_values.empty? && primary_key
          order(arel_table[primary_key].desc).limit(limit).reverse
        else
          to_a.last(limit)
        end
      else
        find_last
      end
    end

https://github.com/rails/rails/blob/4e823b61190388219868744a34dcfe926bad511c/activerecord/lib/active_record/relation/finder_methods.rb#L157

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top