Rails 3 AJAX solution for updating tables?

后端 未结 2 1609
刺人心
刺人心 2021-02-14 21:32

I know this is a popular topic, but I\'ve been searching quite a bit trying to find the answer and strangely haven\'t found anything that has been able to help...

I\'ve

2条回答
  •  礼貌的吻别
    2021-02-14 21:50

    First create a rails endpoint that can get the new entries:

    # config/routes.rb
    match '/records/new_since/:time', :to => 'records#new_since'
    
    # app/controllers/records_controller.rb
    class RecordsController < ApplicationController
      def new_since 
        @records = Record.where('created_at > ?', Time.parse(params[:time]))
        respond_to do |format|
          format.json do
           @records[:time] = Time.now.to_s(:db)
           render :json => @records.to_json
          end
        end
      end
    end
    

    Then, a little javascript on the client side (prototype here):

    setInterval(
      function(){
        new Ajax.Request('/records/new_since/' + $('time') + '.json', {
          method: 'get',
          onSuccess: function(transport){
            var records = transport.response.responseJSON;
            // insert the last checked time into 
    $('time').innerHTML = records.time; // loop over response JSON and do what you want with the data records.each(function(record){ $$('table#records').insert({ bottom: ''+record.attribute+''; }); }); } }); }, 30000 );

    Alternately, instead of sending down json, you can render a template of all the new table rows, and just throw that in too. Less flexible, but a little simpler if you just want to throw the responses at the bottom:

    def new_since
      @records = Record.where('created_at > ?', Time.parse(params[:time]))
      respond_to do |format|
        format.json {} # renders json template
      end
    end
    
    # app/views/records/new_since.html.json.erb
    <% records.each do |record| %>
      <%= record.attribute %>
    <% end %>
    
    setInterval(
      function(){
        new Ajax.Request('/records/new_since/' + $('time') + '.json', {
          method: 'get',
          onSuccess: function(transport){
            var record_rowss = transport.response.responseText;
            $('time').innerHTML = records.time;
            $$('table#records').insert({bottom: record_rows});
          }
        });
      },
      30000
    );
    

提交回复
热议问题