gpt4 book ai didi

ruby-on-rails - 如何在rails Controller 上的ruby中格式化数字,number_with_delimiter仅在 View 中有效

转载 作者:行者123 更新时间:2023-12-04 02:32:45 25 4
gpt4 key购买 nike

我想在将数字插入字符串之前在 Controller 中格式化数字。但是函数 number_with_delimiter() 在 Controller 中不起作用。
我需要将字符串发送到 javascript 插件。

我可以在 View 中运行代码,但我想这不是最好的选择。

@mycarousel_itemList = @mycarousel_itemList + "{url: '" + p.photo.url(:thumb) + 
"', price: '" + p.price.to_s + " €'},"

是否有其他功能可以更改 p.price 的格式?

最佳答案

要直接回答您的问题,请在您的 Controller 中包含以下内容(通常靠近顶部,class 声明下方):

include ActionView::Helpers::NumberHelper

您还可以在模型中包含这个模块(无论 p 是什么类),然后编写一个函数来返回格式化的价格。

然而,此类代码的最佳位置是在帮助程序中,而不是在 Controller 中。将从 View 中调用助手。您的 Controller 应该尽可能短,并且根本不包含任何 View 逻辑。

关于ruby-on-rails - 如何在rails Controller 上的ruby中格式化数字,number_with_delimiter仅在 View 中有效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3596075/

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