0

I have a model named User and in its index.html.erb file, has a link which calls an ajax request responsible for retrieving user's authenticated radars. There it is:

//user.js
function retrieve_radars() {
  $.ajax({
    type: "GET",
    url:  "/radars",

    success: function(data) {
      console.log(data);
    }
  });
}

#app/controllers/radars_controllers.rb
def index
  user    = current_user;
  @radars = Radar.where(:user_id => user.id)
  @radars
end

How could I iterate @radars instance variable in "users/index.html.erb", after the success ajax response? I would like to do something like this:

<% unless @radars.nil? %>
  <table>
  <% @radars.each do |radar| %>
    <tr>
      <td>Name</td>
      <td><%= radar.name %></td>
    </tr>
  <% end %>
  </table>
<% end %>

Any help? Thanks

1 Answer 1

2
//user.js
function retrieve_radars() {
  $.ajax({
    type: "GET",
    url:  "/radars",

    success: function(data) {
      //load the response from radar#index into the div (or any other element
      $("#my_div").html(data); 
    }
  });
}

#app/controllers/radars_controllers.rb
def index
  user    = current_user;
  @radars = Radar.where(:user_id => user.id)
  render :partial => "radars", :layout => false #render partial. 
end

#app/views/radars/_radars.html.erb create partial file
<% unless @radars.nil? %>
  <table>
  <% @radars.each do |radar| %>
    <tr>
      <td>Name</td>
      <td><%= radar.name %></td>
    </tr>
  <% end %>
  </table>
<% end %>
Sign up to request clarification or add additional context in comments.

2 Comments

It worked! Just one detail on your code, I had to create _radars.html.erb partial file, instead of _radar.html.erb :)
My bad, i wrote it from my iPad :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.