gpt4 book ai didi

javascript - 如何从 Rails Controller 设置 morris.js 值

转载 作者:行者123 更新时间:2023-12-02 14:11:12 28 4
gpt4 key购买 nike

我很难在我的运动应用程序中添加圆形图。是否可以将 morris.js 值设置为 Controller 中的变量?我在 Controller 中有 @diet_calories 变量,我想以 60% -> 20% -> 20% 关系显示碳水化合物 -> 蛋白质 -> 脂肪。如果我在脚本标记中设置碳水化合物的值(值:@diet_calories * 0.6),它就不起作用。您有什么建议来解决这个问题吗?

application.html.erb:

<script>
new Morris.Donut({
element: 'diet-circle',
data: [
{ label: "Carbs", value: @diet_calories * 0.6 },
{ label: "Protein", value: @diet_calories * 0.2 },
{ label: "Fat", value: @diet_calories * 0.2 }
]
});
</script>

info_controller.rb:

def diet
if current_user.activity == "Sedentary"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.1) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.1).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.1) + 300).to_i
end
elsif current_user.activity == "Low"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.5) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.5).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.5) + 300).to_i
end
elsif current_user.activity == "Medium"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 1.7) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 1.7).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 1.7) + 300).to_i
end
elsif current_user.activity == "High"
if current_user.goals == "Lose Weight"
@diet_calories = ((@bmr * 2.1) - 300).to_i
elsif current_user.goals == "Maintain Weight"
@diet_calories = (@bmr * 2.1).to_i
elsif current_user.goals == "Add some weight"
@diet_calories = ((@bmr * 2.1) + 300).to_i
end
end

diet.html.erb:

<div id="diet-circle"></div>

最佳答案

尝试:

<script>
new Morris.Donut({
element: 'diet-circle',
data: [
{ label: "Carbs", value: <%= @diet_calories %> * 0.6 },
{ label: "Protein", value: <%= @diet_calories %> * 0.2 },
{ label: "Fat", value: <%= @diet_calories %> * 0.2 }
]
});
</script>

.erb代表嵌入式 Ruby。在 .erb文件来评估 Ruby 代码(例如使用 Controller 中设置的实例变量),您需要使用 <%= ruby code %>

您可以阅读 Erb 模板简介 here

关于javascript - 如何从 Rails Controller 设置 morris.js 值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39555986/

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