kroe761
kroe761

Reputation: 3534

Show view in bootstrap modal not loading data

I trying to load a bootstrap modal from a link_to tag with a show view, from my index view, but the actual data is not being loaded.

controller:

def index
    # to avoid NoMethodError on index.html.erb
    @model = Model.new
end

def show
    @model = Model.find(params[:id])
    logger.debug @model.id # Prints the correct id, so I know the data is loaded from ActiveRecord
end

index.htmnl.erb

<%= link_to show_path(m), remote: true, data: {toggle: "modal", target: "#editModal"} do %>
  Edit
<% end %>

<div class="modal fade" id="editModal" tabindex="-1" role="dialog" aria-labelledby="editModal" aria-hidden="true">
  <h5 class="modal-title" id="modalLabel"><%= @model.name %></h5>
....
</div

When index.html.erb is loaded, if you look in the source, #modalLabel is blank, which makes sense. But, when I click to bring up the modal, it stays blank. @model is not being refreshed from the show view in my controller.

Thanks!

Upvotes: 0

Views: 51

Answers (1)

rmlockerd
rmlockerd

Reputation: 4126

Setting remote: true on the link_to helper causes it to override the default event and fire an asynchronous request when clicked. The event is routed to your controller, but as a Javascript request.

The default convention (i.e., unless you override it) for HTML requests is for Rails to find a corresponding .html.erb view to render (like with your index view). When you render your index, it renders the HTML but at that stage the label is of course empty.

Javascript requests work similarly, except the convention is to look for a corresponding js.erb file. In your case, the request goes to your controller's #show method, which loads your model and looks for (among other possibilities) model/show.js.erb. Because you don't have one, you will likely see something like the following in your logs:

No template found for ArticlesController#show, rendering head :no_content
Completed 204 No Content in 7ms (ActiveRecord: 0.2ms | Allocations: 2893)

So, you need to add some Javascript to update your page in show.js.erb. In your case something like:

document.getElementById('modalLabel').textContent = "<%= @model.name %>";

Upvotes: 1

Related Questions