0

是否可以在 Ruby on Rails 的 javascript 资产中使用帮助程序?我正在尝试使用可用的 helper转换Money对象。在正常视图中它工作正常,但在js.coffee文件中它在 javascript 控制台中显示此错误。Object { fractional: "21050.0", currency: Object, bank: Object }humanized_money<%= humanized_money_with_symbol my_money_object %>

ReferenceError:未定义humanized_money

我的 .js.coffee 文件

$('.select2-hidden-accessible').change ->
  item_id = $(this).find(":selected").val()
  unit_price_input = $(this).parent().find('.unit_price')
  unit_price = 0;
  $.ajax "/items/#{item_id}.json",
    type: 'GET'
    dataType: 'json'
    error: (jqXHR, textStatus, errorThrown) ->
        console.log(textStatus)
    success: (data, textStatus, jqXHR) ->
        console.log(data['unit_price'])
        unit_price = data['unit_price']
  unit_price_input.val(humanized_money unit_price)

解决方案

我已将 show.json.jbuilder 更改为使用 humanized_money 进行响应,而不是在视图中执行此操作。

json.extract! @item, :id, :unit, :created_at, :updated_at
json.unit_price humanized_money @item.unit_price
4

1 回答 1

0

解决这个问题的最简单方法是创建一个initializer文件来赚钱,然后覆盖该to_json方法

class Money
  def as_json(options)
    self.to_f
  end
end

默认情况下,money 列显示的数据比视图中实际需要的数据多。

于 2018-08-01T23:18:56.327 回答