Rails:使用ajax渲染列表

Rails:使用ajax渲染列表

问题描述:

I have a button that links to a details action to show a list of records for a specific reporting_date:

<%= link_to "DETAILS", opportunity_details_path(:reporting_date => date), class: "btn small-bright-button hidden-xs" %>

However, what I want to do now is to render that list below the button in a partial with ajax rather than reloading the whole page and go to the opportunity_details view.

I suppose my button should then contain a remote: true:

<%= link_to "DETAILS", opportunity_details_path(:reporting_date => date), class: "btn small-bright-button hidden-xs", remote: true %>

That's were I'm stuck now.

How do I have to proceed?

                    

我有一个链接到 detailsaction code>的按钮,以显示特定 reporting_date code>的记录列表: p>

   date),类:“ btn小按钮隐藏xs”%>
  code>  pre>

 

但是,我现在要做的是用ajax在按钮下方的列表中部分渲染该列表,而不是重新加载整个页面并进入机会_详细信息视图。 p>

我想我的按钮应该包含一个 remote:true code>: p>

   date),类别:“ btn small-bright-button hidden-xs”,远程:true%>
  code>  pre>

 

那是我现在被困住的原因。 p>

我该如何继续? p>      div>

Loading stuff step by step (and not loading everything at once) via ajax is great for decreasing initial load times and speed up the performance of your app. So kudos for giving it a go. Here's what you can do:

Let's say that the information inside _details.html.erb is wrapped around in a div called .deails-wrapper, so that it becomes

_details.html.erb (or whatever the page is called)

<div class="details-wrapper">
   <p> Some details about this Opportunity </p>
</div>

Remove:

<div class="details-wrapper">

<div> <!-- or whatever element is the greatest parent -->

And keep just the actual information inside _details.html.erb

<p> Some details about this Opportunity </p>

Then what you do, is put the outer-most element below your button:

<%= link_to "DETAILS", opportunity_details_path(:reporting_date => date), class: "btn small-bright-button hidden-xs" %>

Where you want the information to appear, so that it becomes

<%= link_to "DETAILS", opportunity_details_path(:reporting_date => date), class: "btn small-bright-button hidden-xs" %>

<div class="details-wrapper"><div> <!-- Just an empty div for now -->

(Don't forget to add remote: true to the button)

inside the controller add render :opportunity_details:

def opportunity_details
render :opportunity_details
end

Now create a file with the same name as the controller action, in the same folder as the _details.html.erb (or whatever it's called) but not a html.erb but a js.erb file. All the js-code inside this .js.erb will then be executed everytime someone clicks the button. file Do you remember the empty element we put under the button – It will work as our render-point.

opportunity_details.js.erb

$('.details-wrapper').html("<%= escape_javascript(render :partial =>'path_to/details.html.erb') %>");

And this is basically it. You may encounter some errors due to your model not being setup to accept js requests. But all in all you're good to go!