0

我有一个名为 User 的模型,在其 index.html.erb 文件中,有一个链接调用负责检索用户经过身份验证的雷达的 ajax 请求。它是:

//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

在成功的 ajax 响应之后,如何在“users/index.html.erb”中迭代@radars 实例变量?我想做这样的事情:

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

有什么帮助吗?谢谢

4

1 回答 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 %>
于 2013-08-28T17:29:22.623 回答