3

I must pass object Product to javascript. I've read about different methods like:

  1. data-parameter, which I've already use

     <div id="chosen-product-<%=product.id %>" class="chosen-product-panel panel panel-primary"
     data-conversion="<%= product.conversion %>" data-measure="<%= product.measure %>"
    
  2. gem gon (it looks similar)

But my problem is that Product has about 50 attributes. So I don't want to pass 50 data-parameters. How can I pass entire object (is it possible in general?) and then get his attributes in javascript? I've watched http://railscasts.com/episodes/324-passing-data-to-javascript?autoplay=true by Ryan Bates too, but also didn't find solution for my problem.

2 Answers 2

1

You can convert your object to json:

<div id="chosen-product-<%=product.id %>" class="chosen-product-panel panel panel-primary"
 data-conversion="<%= product.conversion.to_json %>" data-measure="<%= product.measure.to_json %>"
Sign up to request clarification or add additional context in comments.

Comments

1

You have to render @product as json. Then send ajax request and get this object.

class ProductsController < ApplicationController
  def get_product
    @product = Product.find(params[:id])
    render json: {product: @product}
  end
end

$.ajax({
   type: 'post',
   url: 'products/get_product',
   success: function (product) {
     //here you get product object with all attributes
   },
   error: function (err) {
    console.log(err);
   },

});

2 Comments

Can you give me more details? I've never used json and ajax is not familiar for me. Should I specify route for this action? And how can I call this ajax function?
It is a bad idea to call the action 'get_product', when normally it should be called 'show'. Also the product Id is missing

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.