【问题标题】:Error making duplicate get requests发出重复的获取请求时出错
【发布时间】:2017-05-01 18:59:29
【问题描述】:

我的控制器操作创建重复记录时遇到问题。我有一个搜索表单,可以检查数据库中的记录,或者如果它不在数据库中,则抓取网站以创建记录。这个相同的操作(我知道不是安静的)也在创建搜索本身的记录,其值为“成功”或“失败”,具体取决于是否可以找到记录。但是,它一直在重复搜索记录。这是form_tag:

<%= form_tag new_search_path, remote: true, method: :get, id: 'etf-lookup-form' do %>
...
   <%= text_field_tag :etf, params[:etf], placeholder: "ETF ticker symbol EX: SPY", autofocus: true, class: 'form-control search-box input-lg', style: "text-transform: uppercase" %>

和控制器:

class SearchesController < ApplicationController
  def new
    if params[:etf]
      @etf = Etf.find_by_ticker(params[:etf].upcase)
      @etf ||= Scraper.new_from_lookup(params[:etf].upcase)
    end

    if @etf.present?
      Search.create(ticker: params[:etf].upcase, user_id: current_user.id, status: "success" )
      render :js => "window.location = '#{etf_path(@etf)}'"
    else
      Search.create(ticker: params[:etf].upcase, user_id: current_user.id, status: "failure" )
      render :js => "window.location = '#{search_path}'"
    end
   end

在呈现新页面之前,终端输出总是显示两次获取请求。我怎么解决这个问题?和/或组织这些控制器操作的更好方法是什么?我还有一个包含显示操作的 EtfsController。以下是来自终端的几个片段:

Started GET "/search/new?utf8=%E2%9C%93&etf=spy&button=" for ::1 at 2017-05-01 20:05:49 -0400
Processing by SearchesController#new as JS
  Parameters: {"utf8"=>"✓", "etf"=>"spy", "button"=>""}
.......
Completed 200 OK in 10ms (Views: 0.1ms | ActiveRecord: 2.0ms)

Started GET "/search/new?utf8=%E2%9C%93&etf=spy&button=" for ::1 at 2017-05-01 20:05:49 -0400
Processing by SearchesController#new as JS
...
Completed 200 OK in 9ms (Views: 0.1ms | ActiveRecord: 2.7ms)
Started GET "/etfs/1" for ::1 at 2017-05-01 20:05:49 -0400
Processing by EtfsController#show as HTML
...
Completed 200 OK in 126ms (Views: 117.9ms | ActiveRecord: 1.2ms)

【问题讨论】:

    标签: ruby-on-rails forms routing


    【解决方案1】:

    也许你可以重构你的代码看起来像这样,问题应该就消失了:

    before_action :set_etf, only: [:new]
    after_action :create_search, only: [:new]
    
    def new
     render js: window_location
    end
    
    private
    
    def create_search
     Search.create(ticker: etf_params, user_id: current_user.id, status: "success" )
    end
    
    def etf_params
     @etf_params ||= params[:etf].to_s.upcase
    end
    
    def set_etf
     @etf = (Etf.find_by_ticker(etf_params) || Scraper.new_from_lookup(etf_params) if etf_params.present?
    end
    
    def window_location
     return "window.location = '#{etf_path(@etf)}'" if @etf.present?
    
     "window.location = '#{search_path}'"
    end
    

    这应该可以解决问题,让我知道它是怎么回事!

    【讨论】:

    • 这不起作用。可能是因为我的搜索是 ajax 请求吗?我在原始评论中放了几个终端 sn-ps
    • 没关系,新表单渲染在哪里?,控制器和动作请...
    猜你喜欢
    • 2021-11-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-10
    • 2017-03-05
    • 2021-04-11
    • 2019-04-19
    • 1970-01-01
    相关资源
    最近更新 更多