1

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

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

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

这是我已经尝试过的。

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

结尾

似乎returnredirect_torender在一个动作中不能很好地发挥作用。

还有其他想法吗?

更新添加了显示操作

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
4

3 回答 3

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

编辑:更新以包括显示动作

于 2015-08-10T18:19:54.677 回答
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
于 2015-08-10T17:56:09.807 回答
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'(参见:最佳实践 ruby​​)

于 2015-08-10T17:59:40.363 回答