制作重复获取请求时出错

时间:2017-05-01 18:59:29

标签: ruby-on-rails forms routing

我遇到一个问题,我的控制器操作正在创建重复记录。我有一个搜索表单,用于检查数据库中的记录,或者如果它不在数据库中,则会搜索网站以创建记录。同样的动作(我知道并不宁静)也创建了搜索本身的记录,其值为“成功”或“失败”,具体取决于是否可以找到记录。但是,它始终重复搜索记录。这是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

终端输出始终在呈现新页面之前显示两次获取请求。我怎么解决这个问题?和/或什么是组织这些控制器操作的更好方法?我还有一个包含show动作的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)

1 个答案:

答案 0 :(得分:0)

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

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

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