0

Is it possible to use helpers in javascript assets in Ruby on Rails? I'm trying to convert Money object Object { fractional: "21050.0", currency: Object, bank: Object } with avaiable helper humanized_money. In normal view it's working properly <%= humanized_money_with_symbol my_money_object %> but in js.coffee file it shows this error in javascript console.

ReferenceError: humanized_money is not defined

My .js.coffee file

$('.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)

Solution

I've changed show.json.jbuilder to response with humanized_money instead doing this in view.

json.extract! @item, :id, :unit, :created_at, :updated_at
json.unit_price humanized_money @item.unit_price
karlosos
  • 1,034
  • 9
  • 25
  • One possible way is convert your json request to ujs instead and inside your js.erb template you can render from erb to javascript, which you can use rails helpers. – nayiaw Jun 17 '16 at 16:15
  • @nayiaw is it possible to use helper in *show.json.jbuilder* file? To have a response with humanized type. – karlosos Jun 17 '16 at 16:17

1 Answers1

0

The easiest way to solve this is creating an initializer file for money, and overwriting the to_json method

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

By default money columns show a bunch more data than actually needed in the views.

Blair Anderson
  • 19,463
  • 8
  • 77
  • 114