Daniel B
Daniel B

Reputation: 82

Javascript in HAML in Javascript

I've got a question that mightve been asked before but i have trouble finding a proper description. I hope someone can help me out.

In the code below on the line where i set var price i want to add the javascript variable accu_id to find a record in my DB through rails. How do I do this in embedded rails in javascript?

 :javascript
    $('#accu').change(function() {
      var accu_id = $("#accu")[0].selectedOptions[0].value
      var price = "#{currency(Product.find_by(id: accu_id).price2)}"
      $('#price_accu').append(price)
    });

Or is there an easier way to do this?

Upvotes: 0

Views: 1056

Answers (1)

You have two options.

  1. You can use AJAX request to get data from database
  2. You can use mapping concept like following

    var data = @processed_data // json data, which contains processed data in json format.
    var accu_id = $("#accu")[0].selectedOptions[0].value
    var price = data.accu_id;

Here the @processed_data contains data like following

@processed_data = currency_calculation

def currency_calculation
   Product.all.map { |product| [product.id, currency(product.price2) ] }.as_json 
end

Example

Assume products table have two entries then the @processed_data contain values like following

{ "1" => "20.00", "2" => "25.50" }

The above data directly assigned to js variable data and accessed like data.key

The first option is best choice and second is possible one.

Note : You can't use js variable inside ruby.

Upvotes: 3

Related Questions