简体   繁体   中英

Proper way to pass data from controller to view when using ajax calls in Rails

Hoping to get some help with the proper way to pass controller data to the view when using ajax calls in Rails.

I have a page where there's a list of profiles. The user on the page can click on any profile and bring up a wish list from that specific profile. The call is made via remote: true in rails so it's an ajax call

class ProfilesController < ApplicationController

  def show
    @list = Profile.find(params[:id]).get_wishlist

      respond_to do |format|
        format.html
        format.js
      end
  end
end

The page will then update a partial on the page that displays the items in the wishlist. Can't figure out the proper way to get the @list data from the controller into the show.js.erb view template. So far, I've tried things along these lines to retrieve the data into the .js.erb view template

var list_data = "<%= j( @list ) %>";

I'm specifically trying to get the result loaded into a JSON object within the js.erb template so I can loop through the results and do some other things. Any help much appreciated or pointing me to where I can find the answer.

What is in the partial? You could just completely replace the partial

<div id=partial>
  <%= render 'partial' %>
</div>

js.erb:

$('#partial').html("<%= j render 'partial', list: @list %>");

For looping you should be able to do: I'm assuming it's a number of items that is returned

<% @list.items.each do |list_item| %>
  $('#partial').append("<%= j render 'list_item_partial', list_item: list_item %>");
<% end %>

Where the list item partial is just the code to display each list item. To be honest I've not used json much so am not going to be much help, other than that you can make your controller code

@list = Profile.find(params[:id]).get_wishlist.to_json

You can use

$('id_of_div').html("<%= escape_javascript(render("partial",list: @list)) %>");

or

$('id_of_div').html("<%= escape_javascript(render("path_to_partial",list: @list)) %>");

add following line to your show.js.erb file

$('id_of_div').html("<%= escape_javascript(render("partial",list: @list)) %>");

or

$('id_of_div').html("<%= escape_javascript(render("path_to_partial",list: @list)) %>");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM