2016-09-06 4 views
-1

Hey Leute, ich entwickle eine Rails-Anwendung, die Zitate in einer Datenbank speichert und dann erlaubt, die Anführungszeichen mit einer einfachen Suche zu durchsuchen. Ich habe das Suchformular implementiert, aber die Ergebnisse erscheinen nicht und ich kann nicht herausfinden warum.Ruby on rails Einfache Suche zeigt keine Ergebnisse an

Controller:

class BasicsController < ApplicationController 
    def quotations 
    @quotations = Quotation.all 
    if params[:search] 
     @quotations = Quotation.search(params[:search]).order("created_at DESC") 
    else 
     @quotations = Quotation.all.order("created_at DESC") 
    end 

    if params[:quotation] 
     @quotation = Quotation.new(params[:quotation]) 
     if @quotation.save 
     flash[:notice] = 'Quotation was successfully created.' 
     @quotation = Quotation.new 
     end 
    elsif 
     @quotation = Quotation.new 
    end 
    if params[:sort_by] == "date" 
     @quotations = Quotation.order(:created_at) 
    else 
     @quotations = Quotation.order(:category) 
    end 
    end 
end 

Modell:

class Quotation < ApplicationRecord 
    def self.search(search) 
    where("author_name LIKE ? OR quote LIKE ?", "%#{search}", "%#{search}") 
    end 
end 

Ansicht:

<%= form_tag basics_quotations_path, :method => 'get' do %> 
<p> 
<%= text_field_tag :search, params[:search], placeholder: "Search Quotations" %> 
    <%= submit_tag "Search", :name => nil %> 
</p> 
<% end %> 
<h3>Quotations</h3> 
<ul> 
<% for quotation in @quotations %> 
    <li><%= h quotation.author_name %>: <%= h quotation.quote %></li> 
<% end %> 
</ul> 
<br/> 
<% if params[:sort_by] == "date" %> 
<%= link_to "Sort by category", :action => :quotations, :sort_by => :category %> 
<% else %> 
<%= link_to "Sort by date", :action => :quotations, :sort_by => :date %> 
<% end %> 
<hr/> 

<h3>New quotation</h3> 
<%= form_for @quotation, :url => { :action => :quotations } do |form| %> 
<fieldset> 
    <legend>Enter details</legend> 
    <div class="form_row"> 
    <%= form.label :author_name %> 
    <%= form.text_field :author_name, :size => 20, :maxlength => 40 %> 
    </div> 
    <div class="form_row"> 
    <%= form.label :category %> 
    <% @cats = [] %> 
    <% Quotation.select('DISTINCT category').map(&:category).each do |element| %> 
     <% @cats << element %> 
    <% end %> 
    <%= form.select(:category,options_for_select([[@cats[0],1],[@cats[1], 2], [@cats[2],3]])) %> 
    </div> 
    <div class="form_row"> 
    <%= form.label :new_category%> 
    <%= form.text_field :category , :size =>20 , :maxlength => 40 %> 
    </div> 
    <div class="form_row"> 
    <%= form.label :quote %> 
    <%= form.text_area :quote, :rows => 2, :cols => 40, :maxlength => 500 %> 
    </div> 
</fieldset> 
<p> 
<div class="form_row"> 
    <%= form.submit 'Create' %> 
</div> 
</p> 
<% end %> 

Routen: Rails.application.routes.draw do get 'basics/quotations' resources :quotation, :quotations # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html end

+0

Wenn Sie die Suche auf der Rails-Konsole ausführen: irgendwelche Ergebnisse? Ist das von Rails generierte SQL in Ordnung? Wenn Sie '' '' '' '' Quotation.all''' zurückgeben, anstatt zu suchen? Ihre Controlleraktion mischt Suche und Erstellung des Angebots. Ich würde das in zwei Aktionen trennen. Sie können die erste '@quotations = Quotation.all' entfernen –

+0

Sie hatten Recht, meine MySql-Abfrage ist falsche Syntax. Ich habe auch eine separate Aktion erstellt, um die Datenbank zu durchsuchen. Danke, dass du dir Zeit genommen hast, auf meine Frage zu antworten. –

Antwort

0

Hast du alles in einer Aktion, die nicht großartig ist. Vielleicht möchten Sie einige der einfachen Rails Tutorials überprüfen.

Zum Thema search insbesondere beachten Sie die letzten vier Zeilen Ihrer Methode ...

if params[:sort_by] == "date" 
    @quotations = Quotation.order(:created_at) 
else 
    @quotations = Quotation.order(:category) 
end 

Also unabhängig von den Ergebnissen Ihrer Suchanfrage, werden Sie @quotations an diesem Punkt mit allen Zitaten ersetzen in entweder created_at oder category bestellen.

+0

Ja, nachdem ich ein wenig mehr gelesen hatte, konnte ich eine separate Aktion erstellen, um die Datenbank nach den Zitaten zu durchsuchen. Ich musste auch meine SQL-Abfrage ändern und dann habe ich es zur Arbeit gebracht. Danke, dass Sie sich die Zeit genommen haben, auf meine Frage zu antworten –

0

Es ist nicht klug, alle Stoffe in einer einzigen Aktion zu platzieren, Ihre Aktion sollte sehr klar und gut definiert sein. Aber Sie können erreichen, was Sie so machen wollten.

class BasicsController < ApplicationController 
    before_action :new_quotation, only:[:search_quotations,:index,:quotations] 

    def search_quotations 
    respond_to do |format| 

     if params[:search] 
     @quotations = Quotation.search(params[:search]).order("created_at DESC") 
     else 
     @quotations = Quotation.all.order("created_at DESC") 
     end 

     if params[:sort_by] == "date" && quotations.present? 
     @quotations = @quotations.order(:created_at) 
     else 
     @quotations = @quotations.order(:category) 
     end   
     format.js{} 
    end 
    end 


def quotations 
    if params[:quotation] 
    @quotation = Quotation.new(quotation_params) 
    if @quotation.save 
     flash[:notice] = 'Quotation was successfully created.'    
    end  
    redirect_to root_path 
    end  
end 

def index 
    @quotations = Quotation.all  
end 


private:  

    def new_quotation 
    @quotation = Quotation.new 
    end 

//If you are using rails4 for later version then go for this line. 
def quotation_params 
    params.require(:quotation).permit(:author_name, :quote,:category) 
end 

end 

Sie müssen tatsächlich die Logik in oben genannten Aktionen trennen und wo ‚Zitat‘ Aktion ein neues Angebot für die Erstellung und ‚seach_quotation‘ gemeint ist, ist es, die alle Angebote für die Suche und es sollte Ursache wir Rückkehr js Antwort gehen dies beim Rendern einer partiellen '_list.html.erb' zu benötigen.

Ihre Ansicht (index.htm.erb) wird so aussehen.

<div> 
    <%= form_tag basics_search_quotations_path, :method => 'get', remote: true do %> 
    <p> 
     <%= text_field_tag :search, params[:search], placeholder: "Search Quotations" %> 
     <%= submit_tag "Search", :name => nil %> 
    </p> 
    <% end %> 
</div> 
    #This partial will be used for refreshing the quotations list via remote true feature for searching and sorting. 
    <div id="quotation_list"> 
    <%= render 'basics/shared/list',{quotations: @quotations} %> 
    </div> 
br/> 
<% if params[:sort_by] == "date" %> 
    <%= link_to "Sort by category", :action => :search_quotations, :sort_by => :category, :remote => true %> 
<% else %> 
    <%= link_to "Sort by date", :action => :search_quotations, :sort_by => :date, :remote => true %> 
    <% end %> 
<hr/> 

<h3>New quotation</h3> 
    <%= form_for @quotation, :url => { :action => "quotations", :controller => "basics" } do |form| %> 
    <fieldset> 
     <legend>Enter details</legend> 
     <div class="form_row"> 
     <%= form.label :author_name %> 
     <%= form.text_field :author_name, :size => 20, :maxlength => 40 %> 
     </div> 
     <div class="form_row"> 
     <%= form.label :category %>  
     <%=  form.select(:category,options_for_select(['Love','Romance','Sadness'])) %> 
     </div> 
     <div class="form_row"> 
     <%= form.label :category%> 
     <%= form.text_field :category , :size =>20 , :maxlength => 40 %> 
     </div> 
     <div class="form_row"> 
     <%= form.label :quote %> 
     <%= form.text_area :quote, :rows => 2, :cols => 40, :maxlength => 500 %> 
     </div> 
    </fieldset> 
    <p> 
    <div class="form_row"> 
    <%= form.submit 'Create' %> 
    </div> 
</p> 
<% end %> 

Hier ist die teilweise mit der Liste der Zitate zeigen /basics/shared/_list.html.erb

<h3>Quotations</h3> 
    <ul> 
    <% for quotation in @quotations %> 
     <li><%= h quotation.author_name %>: <%= h quotation.quote %></li> 
    <% end %> 
    </ul> 

Hier ist die Routen, die Sie routes.rb

resources :quotation, :quotations 
get "basics/search_quotations" => "basics#search_quotations" 
post "basics/quotations" => "basics#quotations" 
root 'basics#index' 
hinzufügen müssen

Anstatt Berechnungen in Sichten durchzuführen, ist es besser, sie im Controller/Modell durchzuführen, falls erforderlich.

so anstelle dieser folgende Zeile in der Ansicht

<% @cats = [] %> 
    <% Quotation.select('DISTINCT category').map(&:category).each do |element| %> 
     <% @cats << element %> 
    <% end %> 
    <%= form.select(:category,options_for_select([[@cats[0],1],[@cats[1], 2], [@cats[2],3]])) %> 

Sie eine Instanzvariable erstellen kann die @categories oder etwas sagen lassen und es verwenden, wie diese

<%= form.select(:category,options_for_select(@categories)) %> 

Und last but not least wir müssen eine search_quotations.js.erb haben, weil wir eine ajax-Anfrage schicken, um das Suchergebnis zu holen und 'js' Antwort zurückzugeben.

$("#quotation_list").html("<%= escape_javascript(render('basics/shared/list', {quotations: @quotations })) %>")