0

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?

2
  • Why are you mixing up pure JS and jQuery? Commented Nov 24, 2016 at 15:17
  • 1
    The best way would be to use AJAX and do the query inside your controller. You can't add JS variables inside an embedded ruby in this context. I guess this could be a good guidance in how to achieve that: stackoverflow.com/a/15422887/615410 Commented Nov 24, 2016 at 15:24

1 Answer 1

3

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.