Steven Ritchie
Steven Ritchie

Reputation: 228

Ajax updating calendar in rails

I have a database of events and i want it to display "today's events".

I have that part working. At the bottom of the page I have a calendar, and when you click on the date i want it to update the listed events to show the NEW dates.

Current I have

<% date = Date.current %>
<% @events.each do |event| %>
<% if event.eventdate === date %>
    <%= event.title %><br>
<% end %>
<% end %>

And the button for example is

<button type="submit" id="dateChange" value="01-01-2013">January 1</button>

And the jQuery is

$(document).ready(function() {
    $('#setdate').html("<% date = Date.tomorrow %>")
 });
});

which updates the html to tomorrow (just as a test).

Two questions -> How do I make it update the actual events listed and how do I pull the value of the button and use it as the Date variable?

Unsure what to do in my controller as well, it's only an index function.

Upvotes: 0

Views: 375

Answers (1)

Mariano Cavallo
Mariano Cavallo

Reputation: 959

Make your controller respond to JS requests and keep the markup generation inside a partial so you can render just that part easily. Also you need to make sure your link/button has the remote attribute set to true or It won't work.

Here's an example I haven't tested it but It should work.

index.html.erb

<div id="events">
    <%= render( 'events_list' ) %>
</div>

_events_list.html.erb

<% date ||= Date.current %>
<% @events.each do |event| %>
    <% if event.eventdate === date %>
        <%= event.title %><br>
    <% end %>
<% end %>
<%= link_to "#{date.tomorrow}", events_path({:date => date.tomorrow}), :remote => true %>

events_controller.rb

...
def index
    @events = Event.all
    @next_date = params[:date]
  respond_to do |format|
    format.html
    format.js # By default this will look for views/events/index.js.erb
  end
end
...

index.js.erb

$('#events').html("<%= escape_javascript render( 'events_list', :date => @next_date ) %>");

Give it a try and let me know.

Upvotes: 1

Related Questions