2014-04-08 54 views
0

Rails 3.2Rails在控制檯中查找範圍

您如何在控制檯中找到最後一個記錄的範圍?

Distributor.find_by_id(2..last) 

謝謝

+0

用'Distributor.where( 'ID> = 2')' – markets

+0

該工程嘗試。我只是該範圍會支持第一個和最後一個。 :( – DDDD

+0

不錯,我添加並用另一個例子回答,希望它有幫助。 – markets

回答

2

你可以簡單地做:

Distributor.where('id >= 2') 

這也適用,但它執行2個查詢:

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

最後一個(限=無)

查找最後一條記錄(如果提供了參數,則爲最後N條記錄)。如果沒有定義訂單,它將按主鍵排序。

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