2015-04-19 64 views
2

如何驗證最後一條記錄是否未在最後一分鐘創建?驗證最後一分鐘內是否創建了最後一條記錄

型號:

class Posts < ActiveRecord::Base 
    validates :author_id, :presence => true 
    belongs_to :author 
    before_save :check_timestamp 

    def check_timestamp  
     IF last_record.created_at(<=1 minute) THEN 
     DO NOT SAVE RECORD 
    end 
end 

它已經一段時間,因爲我拿起這個項目...不知道如果我能做到像上面。

*** LOCAL GEMS *** 

activerecord (4.0.1, 3.2.9) 
activerecord-deprecated_finders (1.0.3) 
... 
rails (4.0.1, 3.2.9) 
railties (4.0.1, 3.2.9) 

回答

1
class Posts < ActiveRecord::Base 
    validates :author_id, :presence => true 
    belongs_to :author 
    validate :check_timestamp 

    def check_timestamp  
     if Posts.last.created_at > 1.minute.ago 
     errors.add(:created_at, 'Something went wront') 
     end 
    end 
end 
+0

邏輯看起來不錯...但獲取未定義的本地變量或方法'last_record' – paulywill

0

我並不需要檢查它是否是最後的記錄,如果它是最近的記錄吧?那麼爲什麼不只是檢查所有記錄的創建日期,看看有沒有超過1分鐘的限制,

class Posts < ActiveRecord::Base 
    belongs_to :author 

    validate :check_timestamp 
    validates :author_id, presence: true 

    def check_timestamp  
     if Posts.where('created_at > ?' 1.minute.ago).exist? 
     errors.add(:created_at, 'Something went wront') 
     end 
    end 
end 

我很擔心它可能會比較慢,但是當我benchmaked它靠在.last方法是快了很多,你可以檢查你的自我。

當我想到它,它確實讓SENCE,因爲鐵軌不會浪費時間解析返回查詢到Post對象,然後檢查created_at,數據庫直接返回truefalse

+0

想象一下,有100萬個帖子的數據庫。檢查所有帖子將比獲得最後一個更快? – dx7

+0

老實說,我試過它在一張小桌子上,就像我說過你可以試驗你的自我,但我認爲如果創建列在索引處將始終是快速的 –

+0

如果created_at被索引,它將比非索引更快。但是Post.last會通過id desc命令發佈帖子,並使用已存在的索引獲取第一個帖子。 – dx7

相關問題