mardi 6 septembre 2016

Ruby on rails Simple Search not displaying results

Hey guys im developing a rails application that stores quotes in a database and then allows you to search through the quotes using a simple search. I have implemented the search form but the results do not appear and I cant figure out why.

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

model:

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

view:

<%= 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 %>

routes: Rails.application.routes.draw do get 'basics/quotations' resources :quotation, :quotations # For details on the DSL available within this file, see http://ift.tt/GVpneB end

Aucun commentaire:

Enregistrer un commentaire