tandy
tandy

Reputation: 1948

Rendering a Rails partial within a single-page app after button-click

How can I render a rails partial within a single-page app after a button-click (assuming there are at least two controllers at play)?

It is unclear to me, regardless of how much material I read:

This is precisely what I am trying to do:

I would like for a user to visit the index page of my application. At that page, they should be able to click a button to "get party event results." The results returned to them should come from the database. This button-click request should be AJAX.

From what I understand, that means

Currently I have:

app/controllers/static_pages_controller.rb

def index
end

app/controllers/party_events_controller.erb

def food_event
end

app/views/static_pages/index.html.erb

<%= button_to "get events", 'layouts/party_events/', remote: true %>

I have 'remote: true' set because this should indicate that the link will be submitted via AJAX.

app/views/static_pages/_party_events.html.erb

  <% food_events.each do |event| %>
    <li><%= event.text %></li>
    <li><%= event.location %></li>
    ---------------------
  <% end %>

Other info, if helpful:

Upvotes: 1

Views: 1334

Answers (1)

jamesy829
jamesy829

Reputation: 428

In your static page, you should have a DOM element available for the ajax to replace or modify.

In your button_to, you should specify the controller and action you would like to hit

In your party_event_controller#action, you can respond with a js and have it render a template, #action.js.erb which will perform the DOM manipulation to replace or update the page.

Similar question asked: Rails - updating div w/ Ajax and :remote => true

An tutorial showing ajax crud with unobstructive javascript: http://stjhimy.com/posts/07-creating-a-100-ajax-crud-using-rails-3-and-unobtrusive-javascript

Upvotes: 1

Related Questions