gpt4 book ai didi

javascript - 如何根据 Rails 中的属性值更改记录的颜色?

转载 作者:行者123 更新时间:2023-12-03 06:26:37 26 4
gpt4 key购买 nike

我有一个带有属性卡路里日期入门模型。我还有带有属性 expected_caloriesUser 模型。当我显示条目列表时,如果每天的卡路里总和超过expected_calories,它应该是红色的,否则应该是绿色的。

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

最佳答案

这是一种非常快速的肮脏方法:

- 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

因此您的 View 将更具可读性(并且逻辑将是可测试的):

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

关于javascript - 如何根据 Rails 中的属性值更改记录的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38622458/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com