あなたはデータベースに引用符を格納し、簡単な検索を使って引用符を検索することができるレールアプリケーションを開発しています。私は検索フォームを実装しましたが、結果は表示されず、理由がわかりません。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で生成されたSQLは正常に見えますか? 検索の代わりに '' 'Quotation.all'''を返すだけですか? コントローラのアクションによって、検索と見積の作成が混在します。私はそれを2つのアクションで分けています。 最初の '@quotations = Quotation.all'を削除することができます –
あなたは誤った構文であるmySqlクエリについて正しくありました。私はまた、データベースを検索するために別個のアクションを作成しました。 –