嘿傢伙我正在開發一個rails應用程序,它將報價存儲在數據庫中,然後允許您使用簡單的搜索在報價單中進行搜索。我已經實施了搜索表單,但結果沒有出現,我不知道爲什麼。Ruby on rails簡單搜索不顯示結果
控制器:
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
型號:
class Quotation < ApplicationRecord
def self.search(search)
where("author_name LIKE ? OR quote LIKE ?", "%#{search}", "%#{search}")
end
end
觀點:
<%= 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 %>
路線: 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
如果您在rails控制檯上執行搜索:任何結果? Rails生成的SQL看起來好嗎? 當你只是返回'''Quotation.all'''而不是搜索? 您的控制器操作混合搜索和創建報價。我會用兩個動作分開。 你可以刪除第一個'@quotations = Quotation.all' –
你說得對mySql查詢是錯誤的語法。我還創建了一個單獨的操作來搜索數據庫。感謝您花時間回覆我的問題 –