1
votes

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:

  • How many controllers I need
  • How many views I need
  • How many actions I need
  • To which action do I assign resources to?

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

  • I need two controllers: 1) StaticPagesController and 2) PartyEventsController. It means that I should have a partial for party events app/views/layouts/_part_events_results.html.erb.
  • I should have an app/views/static_pages/index.html.erb view.
  • It means that I will need a js.erb file somewhere outside of the assets/javascript path.

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:

  • Rails 4.0.0
  • There will eventually be many types of events, e.g. "food", "music". Do I need view partials for each one?
  • Open to any design solution as long as it's a single-page application. I know how to achieve this in PHP/JS, but am struggling to understand how with MVC.
1

1 Answers

1
votes

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