0

I've looked around and read a lot, but can't seem to understand how it works.

I have a bunch of variables in my Controller:

@category1 = @posts.where(category: "1")
@category2 = @posts.where(category: "2")
@category3 = @posts.where(category: "3")

Which i need to display on a chart. (@category1.size e.g.).

The Javascript of the chart accept's this parameters:

{ title: "Category 1",       value:  22,   color: "#2C3E50" },
{ title: "Category 2",       value:  80,   color: "#FC4349" },
{ title: "Category 3",       value:  70,   color: "#6DBCDB" },

I got this working by doing so:

<div id="metrics" data-category1="<%= @category1.size %>">
</div>

and in my JS File :

var $category1 = $("#metrics").data("category1")

and then using the variable created across the File. But i don't think that's a good Practice.

Isn't there a cleaner and Wiser way of achieving this ??

4
  • simply do { title: "Category 2", value: <%= @category2.count %>, color: "#FC4349" }, Commented Apr 9, 2014 at 19:27
  • I have a separate file where the JS is handled. My problem is Passing the Data to that file. Commented Apr 9, 2014 at 19:28
  • If the js file is a partial view, then the variables @cateogory1 & 2 & 3 are shared with this partial view Commented Apr 9, 2014 at 19:30
  • It seems not, i tried it before and it didn't work :/ Commented Apr 9, 2014 at 19:31

2 Answers 2

1

I'd highly suggest looking into the Gon gem: https://github.com/gazay/gon

Without this gem, you're dealing with a very annoying language barrier between Rails and JavaScript. Gon bridges this gap.

After installing the gem, try this in your controller:

@category1 = @posts.where(category: "1")
gon.category1Size = @category1.size

In your JS file:

alert(gon.category1Size);
Sign up to request clarification or add additional context in comments.

Comments

0

You could just return the javascript structure you need directly from rails in an instance variable and then pass that instance variable using javascript like you'r already doing.

Return the chart structure you need from the controller in an instance variable:

{ title: "Category 1",       value:  22,   color: "#2C3E50" },
{ title: "Category 2",       value:  80,   color: "#FC4349" },
{ title: "Category 3",       value:  70,   color: "#6DBCDB" },

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.