gpt4 book ai didi

ruby-on-rails - Rails 中的 DRYing View (number_to_currency)

转载 作者:行者123 更新时间:2023-12-04 01:15:38 25 4
gpt4 key购买 nike

我有类似的代码:
number_to_currency(line_item.price, :unit => "£")
在各种模型中散布我的观点。由于我的应用程序仅以英镑 (£) 交易,所以我不应该将其移动到我的每个模型中,以便 line_item.price按原样返回字符串(即 number_to_currency(line_item.price, :unit => "£")line_item.price 是相同的。我想这样做我应该:

def price
number_to_currency(self.price, :unit => "£")
end

但这不起作用。如 price已在模型中定义,然后 Rails 报告“堆栈级别太深”,当我更改时 def pricedef amount ,然后它提示 number_to_currency没有定义?

最佳答案

number_to_currency 是一个 View 助手,因此它在模型中不可用。

您可以通过在 application_helper.rb 中定义您自己的助手来保存一些击键(因此它可用于所有 View )。例如

def quid(price)
number_to_currency(price, :unit => "£")
end

然后在 View 中调用它:
quid(line_item.price)

关于ruby-on-rails - Rails 中的 DRYing View (number_to_currency),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1400268/

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