2016-07-27 54 views
0

我有條目帶屬性的模型卡路里日期。我也有用戶模型屬性expected_calories。當我顯示條目列表時,如果每天的卡路里總和大於expected_calories,則應該顯示爲紅色,否則應爲綠色。如何根據Rails中它的屬性值更改記錄的顏色?

entries_controller.rb

def index 
@entries = Entry.where(user_id: current_user.id) 
@user = current_user 
if @user.role == 'admin' 
    @entries = Entry.all 
end 

index.html.slim

 h1 Listing entries 

    table.table 
     thead 
     tr 
      th Date 
      th Time 
      th Content 
      th Cal 
      th User 
      th 
      th 
      th 

     tbody 
     - if can? :manage, Entry 
      - @entries.each do |entry| 
      tr 
       td = entry.date 
       td = entry.time.strftime("%H:%M") 
       td = entry.content 
       td = entry.cal 
       td = entry.user.role 
       td = link_to 'Show', entry 
       td = link_to 'Edit', edit_entry_path(entry) 
       td = link_to 'Destroy', entry, data: { confirm: 'Are you sure?' }, method: :delete 

    br 

    = link_to 'New Entry', new_entry_path 
+0

你能分享你到目前爲止有什麼? (特別是在視圖部分) –

+0

我已添加。但仍然不知道如何製作。 –

回答

1

這是這樣做的一個非常快速的骯髒的方式:

- if can? :manage, Entry 
    - @entries.each do |entry| 
    tr(style="background-color: #{entry.calories > current_user.expect_calories ? 'red' : 'green'}) 

我建議你創建一些css類。例如:

.expected-calories { 
    background: green 
} 
.unexpected-calories { 
    background: green 
} 

然後創建在helpers/entries_helper的方法:

def expected_calories_class(user, entry) 
    if user.expected_calories <= entry.calories 
    'expected-calories' 
    else 
    'unexpected-calories' 
    end 
end 

所以,你的看法會更可讀(和邏輯是可測試):

- if can? :manage, Entry 
    - @entries.each do |entry| 
    tr(class=expected_calories_class(current_user, entry)) 
+0

但是我得到了 未定義的方法'<='爲零:NilClass 您的意思是? <=> 提取的源(圍繞線#3): 模塊EntriesHelper DEF expected_calories_class(用戶,條目) 如果user.expected_cal <= entry.cal '預期-卡路里' 別的 '意外-卡路里' –

+0

是' current_user'設置? –

+0

我使用Devise,它應該在它。 –