سؤال

I am a newbie to RoR, and I was using Chartkick with HighCharts to display some graphs from my sqlite database. The graphs are daily and weekly, so I have two .erb-s with the query for each of them, and I want the index.html.erb dynamically change between them in my with a click of a button.

This is the code from the daily_graph.erb:

<div><%= line_graph Product.where(date_time: "2014-03-03 00:00:00".."2014-03-03 23:45:00").group(:date_time).sum(:value) %></div>

This is the code from the weekly_graph.erb:

<div><%= line_graph Product.where(date_time: "2014-03-03 00:00:00".."2014-03-09 23:45:00").group(:date_time).sum(:value) %></div>

How can I manipulate with these views in my index.erb, so when I click the WEEK button, daily_graph will disappear, showing weekly_graph, and the contrary.

هل كانت مفيدة؟

المحلول

Two things:

1) Keep the views dumb. Do the SQL query inside the controller, and set it as a variable that the view accesses. So, it would be:

# Inside your controller

def index
  @daily_products = Product.where(date_time: "2014-03-03 00:00:00".."2014-03-03 23:45:00").group(:date_time).sum(:value)
  @weekly_products = Product.where(date_time: "2014-03-03 00:00:00".."2014-03-09 23:45:00").group(:date_time).sum(:value)
end

Then your view would just be:

<div class="graph"><%= line_graph @weekly_products %></div>
<div class="graph hidden"><%= line_graph @daily_products %></div>

2) the .erb file is used for server-side templating, so switching back and forth would need to happen on the client side. You can have both graphs on the page and use an event handler to disable / show the respective graphs when the button is pushed.

On the index page, lets say you have <button id="flipGraphs">Change</button>

Using jQuery, you can do:

$(function(){ // If you are not familiar with jQuery, this will run when the page is loaded and ready
  $('#flipGraphs').click(function(){
    $('.graph').toggle(); // toggles all of the divs as hidden / shown
  });
});

Also, add this to your application.css file:

.hidden{
  display: none;
}

نصائح أخرى

You want to turn those ERB views into partials... then you can make a new controller action that renders the particular partial your interested in, and you can fetch that controller action with jQuery ajax calls... see: Rails: Rendering Partials through Ajax for more examples

Also conventionally you would not execute model finder methods in the view ... set controller instance variables and reference them instead... this will lead directly to an overall more DRY result.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top