2016-08-19 46 views
0

我想要做的是在category列更改時顯示某些內容。Rails:如何比較以前的值

但最後的數據不顯示任何內容。

例如Event模型中的數據如下所示;

id start_at category 
1 02:00  3 
2 03:00  2 
3 04:00  1 

雖然想什麼我顯示爲以下,最後的數據02:00 (change category)不顯示。

04:00 
03:00 (change category) 
02:00 (change category) 

模式

class Event < ActiveRecord::Base  
    default_scope -> { order(category: :asc, start_at: :asc) } 

    def previous 
    Event.where("id < ?", self.id).order("category ASC, start_at ASC").first 
    end 

視圖

<% @events.each do |event| %> 
    <% if event.previous %> 
     <%= event.start_at %> (change category)<br>  
    <% end %> 
<% end %> 

我知道爲什麼02:00 (change category)不顯示(因爲先前的數據不存在)的原因。

如果您能告訴我如何實現我想要做的事情,我們將不勝感激。

+0

爲什麼不只是刪除'if' ?,我的意思是,如果你想顯示該值,如果'if'是什麼阻止它被顯示...,除非你在做別的,但我不知道。 – fanta

回答

2

你可以用一個簡單的變量做到這一點,你不需要做額外的數據庫調用...

<% category = nil %> 
<% @events.each do |event| %> 
    <% if event.category != category %> 
     <%= event.start_at %> (change category)<br> 
     <% category = event.category %>  
    <% end %> 
<% end %> 
+0

謝謝你的回答,@SteveTurczyn。有用!感謝您瞭解我想要做的事情。 – SamuraiBlue

0

我不知道你想做的事。

如果你只是想知道以前的值,你可以添加一個字段到模型,每當你更新start_at值,你必須記住更新舊值字段(應該從nil或empty_string開始)。

一個更通用的方式來做到這一點,並記住字段的舊值可能會生成一個新的表,它指向不同的模型屬性。這個新表至少應包含:changeable_type:string,changeable_id:integer,attribute_name:string,attribute_value:string(id,created_at,updated_at默認情況下會創建)。然後,你可以添加到這個事件模型

# in this example Change is the name of this new model, and it has -> belongs_to :changeable, polymorphic: true 
class Event < ActiveRecord::Base  
    has_many :changes, as: :changeable 
    default_scope -> { order(category: :asc, start_at: :asc) } 
    after_save :store_old_start_at_value 

    def store_old_start_at 
    old_value = self.changes[:start_at] 
    if old_value # 
     Change.create(changeable: self, attribute_name: 'start_at', attribute_value: old_value[0]) 
    end 
    end 

    def previous_start_values 
    Change.where(changeable_type: self.class.name, changeable_id: self.id, attribute_name: 'start_at').map(&:attribute_value) 
    end 
end 
  • 短版 您可以使用這些模型改變方法上after_save的回調函數來存儲舊值。之前的代碼利用這種方式將該值存儲在多態表中,該表可以存儲任何表和該表的任何字段上的任何更改。