【问题标题】:Rails Rendering a Single Partial after Page LoadRails 在页面加载后渲染单个部分
【发布时间】:2011-08-16 02:38:56
【问题描述】:

我的应用程序中有一个名为 _dashboard.html.erb 的部分页面。在仪表板内部,我有很多调用来渲染不同的部分。其中之一是 _calendar.html.erb 部分,它调用谷歌日历并下拉事件列表。此加载需要时间,我希望在仪表板的其余部分加载后部分加载 _calendar。应该重申,我不希望这是基于点击事件,而是基于页面加载时。

pages_controller.rb

# Logged in to shift
def jump
@title = "#{User.find(session[:user_id]).firstname}'s Dashboard"
@tasks = Task.where(:completed => 0)
@questions = Question.where(:answered => 0)


serv = GCal4Ruby::Service.new
serv.authenticate("email","pass")
cal = GCal4Ruby::Calendar.find(serv, {:title => "Skidmore Center for Sex and Gender Relations"})
#@events = GCal4Ruby::Event.find(serv, {'start-min' => Time.now.utc.xmlschema, 'start-max' => 5.days.from_now.utc.xmlschema })
@events = GCal4Ruby::Event.find(serv, {'start-min' => Time.parse("01/01/2011").utc.xmlschema, 'start-max' => Time.parse("06/01/2011").utc.xmlschema, :calendar => cal.id})

end

跳转是我有仪表板部分呈现的页面。这是调用日历部分的 /app/views/layouts/_dashboard.html.erb 的部分:

<div id="main-content">
  <div class="post">
    <h3>calendar</h3>
    <%= render 'layouts/calendar' %>
  </div>
</div>

还有/app/views/layouts/_calendar.html.erb

<% @events.each do |event| %>
  <% if event.start_time >= Time.now and event.start_time <= 5.days.from_now %><li><%= event.start_time.to_s(:short) %> <%= event.title %></li><% end %>
<% end %>

我认为您应该记住的是,虽然我了解 AJAX 的工作原理,但我几乎没有自己或在 Rails 中编写它的经验。在这里的任何帮助将不胜感激(而且越愚蠢和解释越好!)

谢谢

更新:我使用了 async_partial gem,但现在在从谷歌日历中部分提取事件时遇到问题。没有 async_partial 的部分工作。

【问题讨论】:

  • 我制作了一个基本的 gem 来使用 ajax 加载部分。检查:github.com/apneadiving/AsyncPartial/wiki。如果合适,我会把它作为答案发布
  • 如果您需要更多解释,请告诉我
  • 看起来确实不错,我将研究如何应用它。我究竟如何将 jquery 放入我的应用程序中?
  • 附注,但您应该考虑两件事:1) 使用命名范围,以及 2) 不要将真实的用户名/密码发布到 stackoverflow ;-)
  • :) 我应该解决这个问题并更改我们的密码

标签: ruby-on-rails ajax


【解决方案1】:

在没有 gem 的情况下处理这个问题的一种方法是使用某种事件处理程序来处理页面加载事件,这很常见。例如,使用 jQuery,您可以:

// this get executed when jQuery is made available, which means when 
// your document is ready.
$(function () {

    // you replace the actual calendar content with the piece that is 
    // rendered with your partial
    $("#your-calendar-div-id").replaceWith('<%= escape_javascript(render 'layouts/calendar') %>');

});

【讨论】:

  • $(function () { $("#calendar").replaceWith(' \n \n \n \n \n
  • 01 Sep 11:30 test\ n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\ n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n' ); });
  • ^^ 那是 HTML 输出。知道如何摆脱所有这些 \n 的吗?
  • 您视图中的每一个新行都会转移到\n。这些是 javascript 新行。如果您想摆脱它们,请从您的视图中删除新行。
  • 这应该如何工作?从我所看到的情况来看,部分将在呈现 javascript 的同时加载 - 即。在页面初始加载的同时。没有 AJAX 调用。
  • 在答案中,它说使用“​​某种事件处理程序”。您可以使用按钮单击、ajax 调用等。在这种情况下,它取自一个名为 destroy.js.erb 的文件,该文件使用 JS 渲染器处理销毁操作。
  • 猜你喜欢
    相关资源
    最近更新 更多
    热门标签