Ruby on rails 当项目完成时,使用路线从视图检查

Ruby on rails 当项目完成时,使用路线从视图检查,ruby-on-rails,Ruby On Rails,在后台()从这个外部API获取项目时,使用路由从JS进行检查。路由部分工作正常,但是如何从视图中重用相同的@items\u status,以便Ajax可以实际加载项目并在完成后插入它们 可以动态运行的Live app:() index.html.erb <!-- THIS ALWAYS RETURNS FALSE EVEN WHEN TRUE --> <% if @items_status %> <div class="products"> &l

在后台()从这个外部API获取项目时,使用路由从JS进行检查。路由部分工作正常,但是如何从视图中重用相同的
@items\u status
,以便Ajax可以实际加载项目并在完成后插入它们

可以动态运行的Live app:()

index.html.erb

<!-- THIS ALWAYS RETURNS FALSE EVEN WHEN TRUE -->

<% if @items_status %>
  <div class="products">
    <% @products.each do |product| %>
      <div class="product">
        <%= link_to product.name, product.url %>
      </div>
    <% end %>
  </div>
<% else %>
  <div class="products processing">
    <p>Currently fetching.. come back later</p>

    <!-- Fetch via Ajax later -->

  </div>
<% end %>
<!-- This seems to return true properly though -->

alert("<%= @items_status %>"); 
get '/check_items_loaded', to: 'main#check_items_loaded', as: :check_items_loaded
class MainController < ApplicationController
  def index
    # Delay fetching
    @products = Affiliate.delay.fetch
  end

  def check_items_loaded
    @items_status = Affiliate.where(url: params[:url]).exists?
    respond_to do |wants|
      wants.js
    end
  end
end
require "rest_client"

class Affiliate < ActiveRecord::Base
  def self.fetch
    response = RestClient::Request.execute(
      :method => :get,
      :url => "http://api.shopstyle.com/api/v2/products?pid=uid7849-6112293-28&fts=women&offset=0&limit=10"
    )

    @products = JSON.parse(response)["products"].map do |product|
      product = OpenStruct.new(product)
      affiliate = Affiliate.find_or_create_by(:name => product.name, :url => product.url)
      affiliate.save
    end
  end
end
主控制器.rb

<!-- THIS ALWAYS RETURNS FALSE EVEN WHEN TRUE -->

<% if @items_status %>
  <div class="products">
    <% @products.each do |product| %>
      <div class="product">
        <%= link_to product.name, product.url %>
      </div>
    <% end %>
  </div>
<% else %>
  <div class="products processing">
    <p>Currently fetching.. come back later</p>

    <!-- Fetch via Ajax later -->

  </div>
<% end %>
<!-- This seems to return true properly though -->

alert("<%= @items_status %>"); 
get '/check_items_loaded', to: 'main#check_items_loaded', as: :check_items_loaded
class MainController < ApplicationController
  def index
    # Delay fetching
    @products = Affiliate.delay.fetch
  end

  def check_items_loaded
    @items_status = Affiliate.where(url: params[:url]).exists?
    respond_to do |wants|
      wants.js
    end
  end
end
require "rest_client"

class Affiliate < ActiveRecord::Base
  def self.fetch
    response = RestClient::Request.execute(
      :method => :get,
      :url => "http://api.shopstyle.com/api/v2/products?pid=uid7849-6112293-28&fts=women&offset=0&limit=10"
    )

    @products = JSON.parse(response)["products"].map do |product|
      product = OpenStruct.new(product)
      affiliate = Affiliate.find_or_create_by(:name => product.name, :url => product.url)
      affiliate.save
    end
  end
end
class MainController
affiliate.rb

<!-- THIS ALWAYS RETURNS FALSE EVEN WHEN TRUE -->

<% if @items_status %>
  <div class="products">
    <% @products.each do |product| %>
      <div class="product">
        <%= link_to product.name, product.url %>
      </div>
    <% end %>
  </div>
<% else %>
  <div class="products processing">
    <p>Currently fetching.. come back later</p>

    <!-- Fetch via Ajax later -->

  </div>
<% end %>
<!-- This seems to return true properly though -->

alert("<%= @items_status %>"); 
get '/check_items_loaded', to: 'main#check_items_loaded', as: :check_items_loaded
class MainController < ApplicationController
  def index
    # Delay fetching
    @products = Affiliate.delay.fetch
  end

  def check_items_loaded
    @items_status = Affiliate.where(url: params[:url]).exists?
    respond_to do |wants|
      wants.js
    end
  end
end
require "rest_client"

class Affiliate < ActiveRecord::Base
  def self.fetch
    response = RestClient::Request.execute(
      :method => :get,
      :url => "http://api.shopstyle.com/api/v2/products?pid=uid7849-6112293-28&fts=women&offset=0&limit=10"
    )

    @products = JSON.parse(response)["products"].map do |product|
      product = OpenStruct.new(product)
      affiliate = Affiliate.find_or_create_by(:name => product.name, :url => product.url)
      affiliate.save
    end
  end
end
需要“rest\u客户端”
类附属:get,
:url=>“http://api.shopstyle.com/api/v2/products?pid=uid7849-6112293-28&fts=女性&offset=0&limit=10“
)
@products=JSON.parse(response)[“products”].map do | product|
product=OpenStruct.new(产品)
附属公司=附属公司。查找或创建(:name=>product.name,:url=>product.url)
保存
结束
结束
结束

您必须重新使用用于检查项目是否已提取的路由,而不是查看中的实例
@items\u status

在Ajax部分,您基本上必须不断查询路由以检查它是否完成了抓取,并且在完成后,您必须向另一个路由发出请求以将抓取的项目返回页面

因此,做另一个类似于
get\u items\u fetched
的路由,我认为最好的响应应该是包含这些项目的json数据。例如:

def get_fetched_items
  respond_to do |format|
    format.json do 
      render json: @products
    end
  end
end
您应该在
/get\u items\u fetched.json
获取json数据

更新1:

获取项目状态和项目的正确方法如下:

AJAX部分:

  • 首先将setTimeout更改为setInterval,这样它会自动保持对项目状态的轮询。但是如果您有自己的理由使用setTimeout,那么您可以忽略它

     poll: function() {
       console.log('Ran `poll`');
       // Change here, setTimeout to setInterval.
       window.pollInterval = setInterval(this.request, 3000);
     },
    
  • 其次,检查为轮询请求返回的项_状态,在错误部分不重试

    request: function() {
    
      console.log('Ran `request`');
      $.ajax({
        url: "/check_items_loaded",
        type: "GET",
    
        // Change here ! Added the checking of the item status returned.
        // Why ? Previsouly it wasn't checking at all. So if the request was
        // successful, it meant the items_status was also true.
        success: function(data){
          // Note if the data has the json MIME type, it'll be automatically
          // converted to a JavaScript object.
          if(data.item_status == true) {
            console.log('Items now ready');
            $.restClient.addItems();
    
            // Now you don't have to poll anymore, so clear interval.
            clearInterval(window.pollInterval);
          }
          else 
            console.log('Fetching going on ...');
        },
        error: function() {
          console.log('Request was not completed successfully.');
        }
      });
    },
    
  • 接下来,解析在
    addItems
    的响应中得到的HTML。默认情况下,如果响应是HTML,它将以纯文本形式提供给您

    addItems: function() {
      console.log('Ran `addItems`');
    
      var dataUrl = '/';
    
      $.get(dataUrl, function(data) {
        // Parsing it first.
        var html = $.parseHTML(data);
        $(html).find('.product').appendTo($('body'));
        console.log(html);
      });
    
      console.log('New items were added');
    }
    
  • 现在在后端,
    /check\u items\u done
    路由部分:

     def check_items_loaded
      @items_status = Affiliate.where(url: params[:url]).exists?
      render json: {item_status: @item_status}
     end
    

嗨!这听起来像个计划,谢谢!1.我现在应该怎么看?2.为什么是JSON而不是普通的HTML方式?3.请参阅我的要点,了解我计划如何完成Ajax部分。看起来还好吗?在你看来,我认为你可以创建一个空的可识别占位符,也许是一个div,这样一旦你从后面取回取回的产品,你就可以在那里构建产品。是的,我现在正在检查AJAX代码。啊,是的,我刚刚检查过,所以你正在尝试从你从“/”获得的html页面获取产品,我想没关系。我上个月检查了AJAX部分,这就是原因。我想没问题,但它会像那样工作吗?我的意思是,在使用jquery查询之前,您必须解析返回的html页面。让我们先试试当前的方法。顺便说一句,
restClient
success
请求的
部分始终返回true。我的意思是成功事件意味着请求已成功完成,但这并不意味着返回的项目状态为真。是的,我现在将用这些部分的解决方案更新我的答案。顺便说一句,很抱歉反应太晚,我不得不放弃我的系统一段时间。