2012-03-20 60 views
4

我有一個TradeExecution之間的ActiveRecord關係。我能得到有效記錄。 Model.Find.last

Trade.executions #returns all exeuctions realated to the Trade 

如果我做

Trade.executions.last 

看來似乎返回基於ID的最後執行記錄。

這是基於ID檢索與貿易相關的最後執行記錄的正確方法嗎?

回答

11

不,不能保證給你最高的執行id。如果您沒有指定明確的排序,那麼記錄可以以任何順序從數據庫中出來。事實上,他們看起來像他們排序id只是一個方便的意外。

你應該做的其中之一:

highest_id_execution = trade.executions.order(:id).last 
highest_id_execution = trade.executions.order('id desc').first 

這會給你的執行的trade具有最高id。如果你真的想最近創建的一個,那麼你應該order(:created_at)代替:

most_recent_execution = trade.executions.order(:created_at).last 
most_recent_execution = trade.executions.order('created_at desc').first 

idcreated_at列將幾乎總是以相同的順序,但是你應該說你的意思,以讓事情更清晰的人們,維護你的代碼。

在這兩種情況下,order(:x).lastorder('x desc').first都是完全一樣的,甚至可以解析爲完全相同的SQL,因此無論使用哪一種,對您而言最重要。

+2

+1,您可以添加一個':order'選項給'執行'協會,即'has_many:executions,:order =>「executions.created_at」',這樣'trade.executions.last'返回基於'timestamp'而不是'id'的最後執行。 – 2012-03-20 02:54:59

+0

@KandadaBoggu:真的夠了,但我更喜歡最小的關聯,以避免不必要的ORDER BY和'reorder's。 – 2012-03-20 03:12:18

+0

據我所知,我在非常罕見的情況下使用這種方法,其中超越默認的排序順序使關聯變得直觀。 – 2012-03-20 03:42:26

1

#last將返回基於主鍵的最後一條記錄。如果您的主鍵不是id,那麼您需要更加明確。

這無論是在documentationcode

正如@muistooshort提到的,它不會傷害是明確的:)