【问题标题】:Why is my instance variable empty when I refresh a partial via Ajax request?当我通过 Ajax 请求刷新部分时,为什么我的实例变量为空?
【发布时间】:2016-02-03 15:38:11
【问题描述】:

我的视图上有一个表,我希望每 60 秒自动刷新一次。我按照this question 的答案来实现这一点。在我的表格中,我正在显示来自下面变量 @available_posts_data 的数据。

所以我有一个 Javascript 可以做到这一点:

(document).ready(function () {
    setInterval(refreshPartial, 60000);

});

function refreshPartial() {
  $.ajax({
    url: "posts/refresh_part"
 });
}

然后,在我的 Posts 控制器中,我有这些方法:

def home    
  @posts = Post.order(:id)
  @available_posts_data = get_available_posts_data()
end

#method to refresh the tables of posts and the data.
def refresh_part
  #get updated data based on posts
  @available_posts_data = get_available_posts_data()
  respond_to do |format|
    format.js
  end
end

private 
def get_available_posts_data()
   #this method does something with @posts and returns an array of updated data.
   .
   .
   .
end

现在,有了以上内容,经过 60 秒刷新后,我发现我的表变成了 EMPTY。

原来refresh_part() 中的方法get_available_posts_data() 向我返回了一个空数组,因为@post 是空的!为了让它对我正常工作,我不得不修改 refresh_part 如下:

def refresh_part
  #re-query for the @post variable!
  @posts = Post.order(:id)
  @available_posts_data = get_available_posts_data()
  respond_to do |format|
    format.js
  end
end

为什么我需要重新设置实例变量@post?我有点期待对 posts/refresh_part url 的 Ajax 请求将指向 Post 控制器的同一个实例,并且 @posts 应该可供我使用,因为 home 函数已经设置了一次.

我在这里遗漏了一些简单的东西......在这种情况下,将@post 作为类变量@@post 会更好吗?

【问题讨论】:

    标签: javascript jquery ruby-on-rails ajax


    【解决方案1】:

    我认为您有点误解了实例变量,它们不会在多个请求中持续存在 - 对 Posts 控制器的每个请求都会创建一组新的实例变量。

    所以,它确实需要重新设置,但要删除重复,您可以添加一个前置过滤器:

    class PostsController < ApplicationController
      before_action :find_post
    
      def home 
       #code
      end
    
      def refresh_part
       #code
      end
    
      private
    
      def get_available_posts_data()
       #code
      end
    
      def find_post
        @post = Post.order(:id)
      end
    

    @post 将在控制器的所有功能中可用。如果您向该类添加更多功能但只需要某些功能,您可以这样做:

    before_action :find_post, only: [:home, :refresh_part]
    

    【讨论】:

    • 您好,感谢您的确认。我还是 Rails 的新手,我真的认为每次应用程序运行时只会实例化一个控制器实例。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-15
    • 1970-01-01
    • 2012-12-23
    相关资源
    最近更新 更多