Rails: Search bar isn't working - ruby-on-rails

I'm trying to add a search bar for a database website I created, I found a tutorial and I "think" I did it correct.
When I do a search, such as "Judy Zhang", nothing shows up, even though it is in the database
my vendor.rb/concerns/models/app file
class Vendor < ApplicationRecord
has_many :fotos
def self.search(search)
if search
Vendor.where('lower(contact_name) LIKE ?', "'%#{search.downcase}%'")
else
Vendor.all
end
end
end
I believe I didn't do the coding right. Very new to ruby on rails. What did I do wrong here?
code for index.html.erb/vendors/views/layouts/app
<body>
<div class = "head">
<h1>Vendors </h1>
<div class = "image1" >
<img src= "http://dx.deucex.com/i/logo.png" >
</div>
</div>
</body>
<table>
<tr>
<%= button_to "New Vendor", new_vendor_path, :method => "get" %>
<%= button_to "Inventory", inventories_path, :method => "get" %>
<%= form_tag vendors_path, :method => 'get' do %>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
<% end %>
</tr>
</table>
<table>
<tr>
<th>Company</th>
<th>Contact Name</th>
<th>Phone</th>
<th>Email</th>
</tr>
<% for vendor in #vendors %>
<tr>
<td><%= vendor.company %></td>
<td><%= vendor.contact_name %></td>
<td><%= vendor.phone %></td>
<td><%= vendor.email %></td>
<body>
<div class = "button1" >
<td><%= button_to "Show", vendor_path(vendor), :method => "get" %></td>
</div>
</body>
<td><%= button_to "Edit", edit_vendor_path(vendor), :method => "get" %></td>
<div class = "button3">
<td><%= button_to 'Delete',
vendor_path(vendor),
method: :delete,
data: { confirm: 'Are you sure?'} %></td>
</div>
</tr>
<% end %>
</table>
code for my VendorsController.rb/concerns/controller/app
class VendorsController < ApplicationController
def index
#vendors = Vendor.search(params[:search])
end
def show
#vendor = Vendor.find(params[:id])
end
def new
#vendor = Vendor.new
end
def create
#vendor = Vendor.new(vendor_params)
if #vendor.save
redirect_to #vendor
else
render 'new'
end
end
def edit
#vendor = Vendor.find(params[:id])
end
def update
#vendor = Vendor.find(params[:id])
if #vendor.update (vendor_params)
redirect_to #vendor
else
render 'edit'
end
end
def destroy
#vendor = Vendor.find(params[:id])
#vendor.destroy
redirect_to vendors_path
end
end
private
def vendor_params
params.require(:vendor).permit(:company, :contact_name, :phone, :email, :moq, :cost_per_item, :payment_method, :terms, :turnover, :returns, :notes)
end

Try changing the code in Vendor to
class Vendor < ApplicationRecord
has_many :fotos
def self.search(search)
if search
Vendor.where('lower(name) LIKE ?', "'%#{search.downcase}%'")
else
Vendor.all
end
end
end
My search bar isn't showing up
You should change the following
<% form_tag vendors_path, :method => 'get' do %>
to
<%= form_tag vendors_path, :method => 'get' do %>
# Notice that <%= %> evaluates and prints the output

Related

How to update a record from index in rails

I was trying to update a User record (only the "closed" named column) from the user index's view. This is what I tried. But, it is not working. I used Devise gem to generate views and controllers. But, whatever, How can I update a records one particular value, directly from index(without going to edit's view). It would be very helpful, if someone would help me.
<% #users.each do |user| %>
<tr>
<td> <%= user.last_name %></td>
<td> <%= user.telephone %></td>
<td> <%= form_for user do |f| %>
<% if user.closed %>
<%= f.hidden_field :closed, value: false %>
<%= f.submit "Activate" %>
<% else %>
<%= f.hidden_field :closed, value: true %>
<%= f.submit "Deactivate" %>
<% end %>
<% end %> </td>
<%= link_to 'Remove', user_destroy_path(user), method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
Controller:
def user_index
if current_user.admin?
if params[:user_search].present?
#users = User.search_user(params[:user_search]).super_admin
else
#users = User.super_admin
end
else
if params[:user_search].present?
#users = User.search_user(params[:user_search]).admin
else
#users = User.admin
end
end
respond_to do |format|
format.html
format.csv { send_data User.to_csv, type: 'text/csv', filename: "users.csv" }
end
end
here is my controller. Actually there is also something done to search the users
In your controller, create two methods activate and deactivate.
In controller,
def activate
#user = User.find_by(:id=>params[:id])
#user.update(:closed=>false)
redirect_to #your path
end
def deactivate
#user = User.find_by(:id=>params[:id])
#user.update(:closed=>true)
redirect_to #your path
end
Set your routes as,
patch '#yourcontroller/:id/activate',to:'#yourcontroller#activate' , as: :activate
patch '#yourcontroller/:id/deactivate',to:'#yourcontroller#deactivate' ,as: :deactivate
and finally do changes in your view as,
<% #users.each do |user| %>
<tr>
<td> <%= user.last_name %></td>
<td> <%= user.telephone %></td>
<td> <%if user.closed?%>
<%= link_to 'activate',activate_path(id:user.id), method: :patch%>
<%else%>
<%= link_to 'deactivate',deactivate_path(id:user.id), method: :patch%>
<% end -%> </td>
<%= link_to 'Remove', user_destroy_path(user), method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
Its helpful pls up-vote!

Rails 5: Displaying object value not ID

I have a simple app for a skydiving dropzone. Parachute packers keep track of their packsjobs. There are several packjobs for each parachute rig.
I have the Show view working perfectly by showing the rig_type_number under the rig detail (ie Reflex #2) but I can only get the rig_id to work in the same column for the index. Ideally, I'd like to so the rig_type_number as well instead of the ID.
How can I reference in the view something to the effect of #rigs.rig_type_number?
This makes sense to me, but does not work:
<td><%= link_to packjob.rig_id,rig_path(rig.rig_type_number) %>
Will I have to a where clause for the index controller?
db:
class CreatePackjobs < ActiveRecord::Migration[5.1]
def change
create_table :packjobs do |t|
t.string :packer
t.string :rig
t.references :rig, foreign_key: true
t.timestamps
end
end
end
class CreateRigs < ActiveRecord::Migration[5.1]
def change
create_table :rigs do |t|
t.boolean :rig_status
t.string :rig_type_number
t.integer :rig_season_jumpnum
t.date :rig_res_last
t.string :rig_res_who
t.timestamps
end
end
end
packjobs_controller:
class PackjobsController < ApplicationController
def index
#packjobs = Packjob.paginate(page: params[:page]).order('id DESC')
#rigs = Rig.where(rig_status: "t")
end
def show
#packjob = Packjob.find(params[:id])
#rig = Rig.find(#packjob.rig_id)
end
def new
#packjob = Packjob.new
#rigs = Rig.where(rig_status: "t")
end
def edit
#packjob = Packjob.find(params[:id])
#rigs = Rig.where(rig_status: "t")
end
def create
#packjob = Packjob.new(packjob_params)
#rigs = Rig.where(rig_status: "t")
if #packjob.save
redirect_to #packjob
else
render 'new'
end
end
def update
#packjob = Packjob.find(params[:id])
#rigs = Rig.where(rig_status: "t")
if #packjob.update(packjob_params)
redirect_to #packjob
else
render 'edit'
end
end
def destroy
#packjob = Packjob.find(params[:id])
#packjob.destroy
redirect_to packjobs_path
end
private
def packjob_params
params.require(:packjob).permit(:packer, :rig_id)
end
def rigs_params
params.require(:rig).permit(:rig_status, :rig_type_number)
end
end
show.html.erb:
<p>
<b>Datestamp:</b>
<%= #packjob.created_at.strftime("%m/%d/%Y %I:%M %P") %><br>
</p>
<p>
<strong>Packer:</strong>
<%= #packjob.packer %>
</p>
<p>
<strong>Rig:</strong>
<%= #rig.rig_type_number %><br>
</p>
<%= link_to 'Edit', edit_packjob_path(#packjob) %> |
<%= link_to 'Back', packjobs_path %>
index.html.erb:
<h1>Listing Packjobs</h1>
<%= link_to 'New Packjob', new_packjob_path %> | <br>
<br>
<div class="digg_pagination">
<%= will_paginate #packjobs, :container => false %>
</div>
<table id=listtable CELLPADDING="4" border="1">
<tr class="headerBlue" >
<th>Datestamp</th>
<th>Packer</th>
<th>Rig</th>
<th colspan="3"></th>
</tr>
<% #packjobs.each do |packjob| %>
<tr class="<%= cycle('rowA', 'rowB') %>">
<td><%= link_to packjob.created_at.strftime("%m/%d/%Y %I:%M:%S %P"),packjob_path(packjob.id) %></td>
<td><%= packjob.packer %></td>
<td><%= link_to packjob.rig_id,rig_path(packjob.rig_id) %>
<td><%= link_to 'Show', packjob_path(packjob) %></td>
<td><%= link_to 'Edit', edit_packjob_path(packjob) %></td>
<td><%= link_to 'Destroy', packjob_path(packjob),
method: :delete,
data: { confirm: 'Are you sure?' } %></td>
<% end %>
</tr>
</table>
<div class="digg_pagination">
<div class="page_info">
<%= page_entries_info #packjobs %>
</div>
<%= will_paginate #packjobs, :container => false %>
</div>
<br><%= link_to 'New Packjob', new_packjob_path %> |
EDITED:
models:
class Packjob < ApplicationRecord
belongs_to :rig
validates :packer, presence: true
validates :rig_id, presence: true
self.per_page = 25
end
class Rig < ApplicationRecord
has_many :packjobs
validates :rig_type_number, presence: true
self.per_page = 25
end
Your associations are set correctly, you can reference the associated object like this:
<td><%= link_to packjob.rig.rig_type_number,rig_path(packjob.rig_id) %>
You can call it as below in case you have has_one :rig association in PackJob model :
<td><%= link_to packjob..rig.rig_type_number,rig_path(packjob.rig_id) if packjob.rig.present? %> </td>

Nested class is saving but not displaying correctly.

I'm working through the rails intro guide but using 'stocks' instead of 'articles' and 'time_detlas' instead of 'comments' my issue is that it seems to be saving time_deltas correctly, I think I checked that correctly but the show of the stock just adds an extra blank row to the table of time_deltas no numbers show. Any suggestions why?
Stocks controller:
class StocksController < ApplicationController
def new
#stock = Stock.new
end
def index
#stocks = Stock.all
end
def create
# XXX Add columns for delta and current standing when we get there
# they can intiate to nil
#stock = Stock.new(stock_params)
if #stock.save
redirect_to #stock
else
render 'new'
end
end
def show
#stock = find_stock
#time_delta = #stock.time_deltas.build
end
def edit
#stock = find_stock
end
def update
#stock = find_stock
if #stock.update(stock_params)
redirect_to #stock
else
render 'edit'
end
end
def destroy
#stock = find_stock
#stock.destroy
redirect_to stocks_path
end
private
def stock_params
params.require(:stock).permit(:name, :hashtag)
end
def find_stock
return Stock.find(params[:id])
end
end
Time Delta Controller
class TimeDeltasController < ApplicationController
def create
#stock = Stock.find(params[:stock_id])
#time_delta = #stock.time_deltas.create(time_delta_params)
redirect_to stock_path(#stock)
end
private
def time_delta_params
params.require(:time_delta).permit(:start, :length)
end
end
Show for the stock
<h1> Stock </h1>
<table>
<tr>
<th>Stock</th>
<th>Hashtag</th>
</tr>
<tr>
<td><%= #stock.name %></td>
<td><%= #stock.hashtag %></td>
</tr>
</table>
<h3>TimeDeltas: </h2>
<table>
<tr>
<th>Start</th>
<th>Length</th>
</tr>
<% #stock.time_deltas.each do |time_delta| %>
<tr>
<td><%= #time_delta.start %></td>
<td><%= #time_delta.length %></td>
</tr>
<% end %>
</table>
<h3>Add a TimeDelta:</h2>
<%= form_for([#stock, #stock.time_deltas.build]) do |f| %>
<p>
<%= f.label :start %><br>
<%= f.text_field :start %>
</p>
<p>
<%= f.label :length %><br>
<%= f.text_field :length %>
</p>
<p>
<%= f.submit %>
</p>
<% end %>
<%= link_to 'Back', stocks_path%>
<%= link_to 'Edit', edit_stock_path(#stock)%>
Any help is appreciated, thank you!
just remove # from time_delta
<% #stock.time_deltas.each do |time_delta| %>
<tr>
<td><%= time_delta.start %></td>
<td><%= time_delta.length %></td>
</tr>
<% end %>
up
You need # only to be able to share this var with your view. Eg: If you add this to your show action: #time_deltas = TimeDelta.all
you can show time_deltas in your view.
like:
<% #time_deltas.each do |td|%>
<%= td.start%>
<% end %>

Having Trouble With Kaminari Gem

I'm trying to paginate multiple tables with the Kaminari Gem. I've tried to do this by generating an array in my application controller, like so:
#paginate = %w(errors messages subscribers).page(params[:page]).per(15)
I've then taken #paginate and used it in one of my partials than renders the tables, like so:
<%= paginate #paginate %>
But I keep receiving a:
NoMethodError in Admin::ApplicationController#index
undefined method `page' for ["errors", "messages", "subscribers"]:Array
Here is the code that I've got:
Application_Controller.rb
class Admin::ApplicationController < InheritedResources::Base
protect_from_forgery
include ResourcesHelper
layout "admin"
#Setup
before_filter :set_resource_variable
before_filter :set_pagination_variable, only: :index
#Authentication
skip_before_filter :authenticate_user!
before_filter :authenticate_admin!
#Authorization
skip_before_filter :check_authentication
#Index
#Custom Index For Application/Index (no inheritance)
def index
#users = User.all
#attributes = %w(messages subscribers)
#paginate = %w(errors messages subscribers).page(params[:page]).per(15)
end
#Create
def create
create! { collection_path }
end
#Update
def update
update! { collection_path }
end
private
#Set Model Variable
def set_resource_variable
#resource = self.resource_class
#model = "#{#resource}".downcase.to_sym
end
#Pagination
def set_pagination_variable
#params[:page] ||= "1"
end
#Strong Params
def permitted_params
attributes = attributes(#resource) + %w(user_id admin_id) + [image_pages_attributes: [:caption, image_attributes: [:image]]]
params.permit(#model => attributes)
end
end
_table.html.erb
<h2><%= model %></h2>
<% unless collection.blank? %>
<table class="sort">
<thead>
<tr>
<% model.attribute_names.each do |attr| %>
<th><%= model.human_attribute_name(attr) %></th>
<% end %>
<th colspan="2"> </th>
<% if model.name == "Error" %><th> </th><% end %>
</tr>
</thead>
<tbody>
<%= render partial: "admin/resources/table/row", collection: collection, as: :resource, locals: {model: model} %>
</tbody>
</table>
_row.html.erb
<tr data-link="<%= polymorphic_path([:admin, resource]) %>">
<% model.attribute_names.each do |attr| %>
<td><%= resource.send(attr) %></td>
<% end %>
<% if model.name == "Error" %>
<td><%= link_to "Read", admin_error_read_path(resource.id), method: :put, remote: :true, class: "read" %></td>
<% end %>
<td><%= link_to "Edit", edit_polymorphic_path([:admin, resource]) %></td>
<td><%= link_to "Delete", polymorphic_path([:admin, resource]), method: :delete, data: {confirm: "Are you sure?"} %></td>
If you need anything else, let me know and I'll put it up.
Thank you!!
You're not setting "page" properly. It should always be like this:
paginate(:page => params[:page], :per_page => 15)
So in your example
#paginate = %w(errors messages subscribers).page(params[:page]).per(15)
What you really want is:
#paginate = %w(errors messages subscribers).paginate(:page => params[:page], :per_page => 15)

Tabbed menus broke my geocoder search functionality

I'm fairly new to Ruby on Rails, making a directory type of website as a personal project to learn.
In my app, I implemented Geocoder search so the user can search for places/locations near them, the search worked perfect. But then when I added tabbed menus to categorize what type of places are available it broke the search.
I think I know why it's broken but not sure how to fix it. The tabs are showing the #schools, #restaurants, and #businesses variables, how can I get the tabs to show the search results and not those variables? Those variables should only show up when there is no search executed, but they also show up when the search is executed.
Here's my code:
Places Controller:
class PlacesController < ApplicationController
before_filter :authenticate_user!, except: [:index]
def index
if params[:search].present?
#places = Place.near(params[:search], 50, :order => :distance)
else
#places = Place.all
end
#schools = Place.where("category = ?", "School")
#restaurants = Place.where("category = ?", "Restaurant")
#businesses = Place.where("category = ?", "Business")
end
Places Index.html.erb:
<% if user_signed_in? %>
<div class="row">
<h2>Newly Added Places</h2>
<%= form_tag places_path, :method => :get do %>
<%= text_field_tag :search, params[:search], placeholder: "Enter your zipcode or city", class: "search-query" %>
<%= submit_tag "Search Nearby", :name => nil, class: "btn"%>
<% end %>
<ul class="nav nav-tabs">
<li>Schools</li>
<li>Restaurants</li>
<li>Businesses</li>
</ul>
<div class="tab-content">
<div class="tab-pane active" id="tab1">
<%= render :partial => "places", :locals => {:places_container => #schools} %>
</div>
<div class="tab-pane" id="tab2">
<%= render :partial => "places", :locals => {:places_container => #restaurants} %>
</div>
<div class="tab-pane" id="tab3">
<%= render :partial => "places", :locals => {:places_container => #businesses} %>
</div>
</div>
</div>
<br />
<% else %>
<%= render 'static_pages/home' %>
<% end %>
Places partial(_places.html.erb):
<table class="table table-hover table-condensed">
<thead>
<tr>
<th>Image</th>
<th>Name</th>
<th>Address</th>
<th>State</th>
<th>City</th>
<th>Type</th>
<th>Website</th>
</tr>
</thead>
<% places_container.each do |place| %>
<tr>
<th><%= image_tag place.image(:medium)%></th>
<th><%= link_to place.name, place %></th>
<td><%= place.address %></td>
<td><%= place.state %></td>
<td><%= place.city %></td>
<td><%= place.category %></td>
<td><%= place.website %></td>
<% if current_user.admin? %>
<td><%= link_to 'Edit', edit_place_path(place) %></td>
<td><%= link_to 'Destroy', place, method: :delete, data: { confirm: 'Are you sure?' } %></td>
<% end %>
</tr>
<% end %>
</table>
Your tabbed results are ignoring the search parameter because you aren't using the #places relation built from the search parameter. To fix, change this code:
def index
if params[:search].present?
#places = Place.near(params[:search], 50, :order => :distance)
else
#places = Place.all
end
#schools = Place.where("category = ?", "School")
#restaurants = Place.where("category = ?", "Restaurant")
#businesses = Place.where("category = ?", "Business")
end
to:
def index
if params[:search].present?
#places = Place.near(params[:search], 50, :order => :distance)
else
#places = Place.scoped # use 'scoped', not 'all', to avoid triggering the query immediately
end
#schools = #places.where("category = ?", "School")
#restaurants = #places.where("category = ?", "Restaurant")
#businesses = #places.where("category = ?", "Business")
end

Resources