2015-05-03 43 views
0

我有一個Rails 3.2.21應用程序,我添加了一些基本的時鐘功能。我需要構建一個名爲current_clock_event的作用域,該作用域將查找用戶的最後一條記錄,其中clock_out: nil因此實質上,將獲取的記錄是用戶的最後ClockEvent記錄,該記錄在clock_out中沒有值。這是我想要傳遞給我的控制器/視圖。在ActiveRecord中獲取最後的不完整記錄或新的

class ClockEvent < ActiveRecord::Base 
    attr_accessible :clock_in, :clock_out, :total_hours, :user_id 

    scope :current_clock_event, where(clock_out: NIL).last 
end 

正如你可以看到我寫了一個很簡單的範圍拉的紀錄,其中在理論上clock_out: NIL,就這樣還要拉過去的不完全記錄。我認爲這工作正常,但我需要弄清楚如何在控制器中訪問它,並且有一些條件來拉動current_clock_event或者在最後一條記錄完成時實例化一個新的時鐘事件(填充了clock_inclock_out

因此,我正在扼殺我的控制器,但是如何做到這一點卻遇到了困難。

class ClockEventsController < ApplicationController 

    def index 
    @clock_event = current_user.current_clock_event # need to figure out this part to fetch the record or if the record is complete instantiate a ClockEvent.new for the user. 
    respond_to do |format| 
     format.html # index.html.erb 
     format.js 
    end 
    end 
end 

I 2年前做了這一切,但失去了事故回購,所以我沒有什麼可參考和我的腦霧對如何退出這個功能的排序編寫代碼。

任何幫助,將不勝感激。如果你需要更多的例子或進一步的解釋,請讓我知道。

回答

1

你可能想嘗試這樣的:

class ClockEvent 

    belongs_to :user 

    # you might want to add an order here... 
    scope :last_clock_event, -> { where("clock_out NULL").last } 

    def completed? 
    clock_in.present? && clock_out.present? 
    end 

end 

class User 

    has_many :clock_events 

    def current_clock_event 
    ce = clock_events.last_clock_event 
    ce.completed? ? ClockEvent.new : ce 
    end 

end 

class ClockEventsController < ApplicationController 

    def index 
    @clock_event = current_user.current_clock_event 
    render :index 
    end 

end 

ClockEvent實例定義的completed?方法可以讓你判斷你的實例被視爲完成與否。

User級別定義的current_clock_event方法允許您定義邏輯以返回最後一個時鐘事件記錄或完成時返回的新記錄。

index方法非常簡單。

+0

這實際上是一個很好的處理方法。我一直專注於控制器,並將邏輯放在那裏,我沒有想到在模型方面處理它。因此,這應該允許我在索引操作中將'@ clock_event'傳遞給我的表單,並允許它們在不完整事件或新事件的所有時間內進/出時鐘。只要確定我正在閱讀這個權利。我喜歡這個解決方案,今天我會試一試,並且會回報:)非常感謝! – nulltek

+0

這樣的事情呢(看我發佈的答案) – nulltek

+0

對不起我的答案格式,但希望你能得到我想要做的事情的要點。我正在將時鐘事件緩存到一個變量的內存中以避免過多的數據庫命中,並且我正在'clock_event'方法中定義行爲,以查看最後一個不完整的'ClockEvent'或實例化一個新的'ClockEvent ' – nulltek

0

我玩了一些代碼,並能夠得到一些重構幫助,使事情更乾淨。在User模型中,我將current_clock_event重構爲clock_event,似乎能夠使代碼更清晰一些,儘管它沒有經過測試,現在只是被剔除了。讓我知道你的想法。

class ClockEvent 
    belongs_to :user 

    scope :incomplete, -> { where(clock_out: nil) } 
    scope :complete, -> { where.not(clock_out: nil) } 

    def completed? 
    clock_in.present? && clock_out.present? 
    end 
    end 

    class User 
    has_many :clock_events 

    def clock_event 
     @clock_event ||= clock_events.incomplete.last || clock_events.new 
    end 
    end 

    class ClockEventsController < ApplicationController 

    def index 
     @clock_event = current_user.clock_event 
     render :index 
    end 
    end