0

我在我的rails 4應用程序上使用elasticsearch來搜索我的文章。在另一個Rails中使用控制器中的方法

但是,如果找不到文章,它會重定向到提醒用戶未找到結果的頁面,並允許請求頁面。而不是它說「沒有找到結果」我希望它說「沒有找到______的結果」,其中需要搜索欄查詢。

爲了獲得查詢,我在articles_controller中定義了一個方法,但它不會顯示在頁面上,因爲「無結果頁面」使用不同的控制器。

在這種情況下將方法拉到另一個控制器或視圖上的最佳方法是什麼?無法找到我想要做的事情的直接答案。非常感謝你。

articles_controller:

def index 

    if params[:query].present? 
     @articles = Article.search(params[:query], misspellings: {edit_distance: 1}) 
    else 
     @articles = Article.all 
    end 

    if @articles.blank? 
     return redirect_to request_path 
    end 

    get_query 
    end 

    private 

    def get_query 
    @userquery = params[:query] 
    end 

new.html.erb(視圖 「沒有找到結果」 頁面使用不同的控制器不是文章頁):

<body class="contactrequest"> 
<div class="authform" style="margin-top:15px"> 
    <%= simple_form_for @request, :url => request_path do |f| %> 

    <h3 style = "text-align:center; color:red;">No results found. <%= @userquery %></h3> 
    <h1 style = "text-align:center; color:black;">Request a Page</h1> 
    <h5 style = "text-align:center; color:black; margin-bottom: 25px;">Our experts will gather the information,<br> and have your page us ASAP!</h5> 

    <%= f.error_notification %> 

    <div class="form-group"> 

    <%= f.text_field :email, placeholder: 'Email', :autofocus => true, class: 'form-control' %> 
    </div> 
    <div class="form-group"> 

    <%= f.text_field :subject, placeholder: 'Item/Page Requested', class: 'form-control' %> 
    </div> 
    <div class="form-group"> 

    <%= f.text_area :content, placeholder: 'Any additional details...', class: 'form-control', :rows => '5' %> 
    </div> 

    <%= f.submit 'Request it', :class => 'btn btn-lg btn-danger btn-block' %> 

<% end %> 

由於你可以看到我已經嘗試調用@userquery方法在視圖頁面上顯示,但它不顯示,因爲它是在不同的控制器上定義的。任何建議都會很棒。

回答

1

我建議你呈現結果,並沒有從相同的控制器/視圖的結果。一個很好的乾淨的方式來做到這一點是部分。你的看法可能類似於:

<% if @articles.blank? %> 
    <%= render 'no_results' %> 
<% else %> 
    <%= render 'results' %> 
<% end %> 

然後,你會簡單地創建_no_results.html.erb加上當前new.html.erb內容填充它,併爲您的名義結果頁面做同樣的(有部分_results.html.erb)。

+1

正確。這樣,你就擁有了你所需要的所有環境。 –

+0

嗯,得到'Template is missing'錯誤。 – Kathan

+1

您是否將偏分量與索引視圖放在同一個文件夾中?看起來應該是'app/views/articles'。 –

相關問題