如果找到一条记录执行show action

时间:2015-08-10 17:24:45

标签: ruby-on-rails ruby actioncontroller elasticsearch-rails

我想知道执行下一个任务的最佳做法是什么。

我有一个搜索结果可以显示索引操作。每个单独的记录都会通过show action显示在弹出窗口中。

如果只找到一条记录,我想做的就是执行弹出窗口。

这是我已经尝试过的。

def index
 @companies = Company.search(params[:query]).results
 @count = @companies.total
 if @count == 1
   return
   render company_path       
 end

似乎返回 redirect_to 渲染在一个操作中效果不佳。

还有其他想法吗?

更新添加了show action

def show
 sleep 1/2
 client = Elasticsearch::Client.new host:'127.0.0.1:9200', log: true
 response = client.search index: 'companies', body: {query: { match: {_id: params[:id]} } }
 @company = response['hits']['hits'][0]['_source']
   respond_to do |format|
     format.html # show.html.erb
     format.js # show.js.erb
     format.json { render json: @company }
   end
  # more code 
end

3 个答案:

答案 0 :(得分:1)

返回肯定是在扼杀你,但你正在尝试渲染/重定向到特定资源的路径而不指定资源。我已经采取了一些可能对您有所帮助的事情:

class MyController
  before_action :find_companies, only: :index
  before_action :find_company, only: :show
  before_action :show_company_if_matched, only: :index

  def index
    # do whatever you were doing here...
  end

  def show
    respond_to do |format|
      format.html # show.html.erb
      format.js # show.js.erb
      format.json { render json: @company }
    end
    # more code 
  end

  private

  def find_companies
    @companies = Company.search(params[:query]).results
  end

  def find_company
    client = Elasticsearch::Client.new host:'127.0.0.1:9200', log: true
    response = client.search index: 'companies', body: {query: { match: {_id: params[:id]} } }
    @company = response['hits']['hits'][0]['_source']
  end

  def show_company_if_matched
    redirect_to company_path(@comapnies.first) if @companies.total == 1
  end
end

编辑:已更新,以包含展示操作

答案 1 :(得分:0)

从控制器中删除return。如果我理解了你的问题,这应该会导致你正在寻找的行为:

 if @count == 1
   render company_path  
 else
   # Do something else
 end

如果控制器中存在您不想执行的后续代码,则可以按如下方式渲染并返回:

 if @count == 1
   render company_path and return
 else
   # Do something else
 end

答案 2 :(得分:0)

这是正确的语法:

def index
 @companies = Company.search(params[:query]).results
 @count = @companies.total
 if @count == 1
   render company_path # no params ?
   return
 else
   redirect_to root_path
   return
 end
end

渲染后使用return或重定向它是一种好习惯,因为在某些情况下'render'或'redirect_to'不会'return'(cf:best practice ruby​​)