Rails search with multiple queries not working - ruby-on-rails

I know my code is clunky, but I am trying to have a form with multiple text boxes for different columns in my GUEST database. The form is not working and all my guest entries are still listed (the list is not narrowed down by the search). If anyone could possibly point me in the correct direction that would be awesome. Also how could the guest.rb code be more concise?
Controller:
def index
#guests = Guest.all
if params[:search_first_name]
#guests = Guest.search_first_name(params[:search_first_name])
end
if params[:search_last_name]
#guests = Guest.search_last_name(params[:search_last_name])
end
if params[:search_email]
#guests = Guest.search_email(params[:search_email])
end
if params[:search_phone]
#guests = Guest.search_phone(params[:search_phone])
end
end
guest.rb
def self.search_first_name(query)
# where(:email, query) -> This would return an exact match of the query
where("first_name like ?", "%#{query}%")
end
def self.search_last_name(query)
# where(:email, query) -> This would return an exact match of the query
where("last_name like ?", "%#{query}%")
end
def self.search_email(query)
# where(:email, query) -> This would return an exact match of the query
where("email like ?", "%#{query}%")
end
def self.search_phone(query)
# where(:email, query) -> This would return an exact match of the query
where("phone like ?", "%#{query}%")
end
index.html:
<%= form_tag(guests_path, :method => "get", class: "navbar-form", id: "search-form") do %>
<div class="input-append col-sm-10">
<div class="row">
<div class="col-sm-4">
<p><%= text_field_tag :search_first_name, params[:search_first_name], placeholder: "First Name", style: "width:100%;" %></p>
<p><%= text_field_tag :search_last_name, params[:search_last_name], placeholder: "Last Name", style: "width:100%;" %></p>
</div>
<div class="col-sm-4">
<p><%= text_field_tag :search_email, params[:search_email], placeholder: "Email Address", style: "width:100%;" %></p>
<p><%= text_field_tag :search_phone, params[:search_phone], placeholder: "Phone Number", style: "width:100%;" %></p>
</div>
<div class="col-sm-4">
</div>
<%= submit_tag 'Search Guests' %>
</div>
</div>
<% end %>
<table class="table table-hover col-sm-12">
<thead>
<tr>
<th>Guest ID</th>
<th>Guest Name</th>
<th>Email</th>
<th>Phone</th>
<th></th>
</tr>
</thead>
<tbody>
<% #guests.each do |guest| %>
<tr>
<td>G-00<%= guest.id %></td>
<td><%= guest.first_name %> <%= guest.last_name %></td>
<td><%= guest.email %></td>
<td><%= guest.phone %></td>
<td style="text-align:right;"><%= link_to 'View Guest Profile', guest, :class => "btn btn-sm btn-success" %> <%= link_to 'Edit', edit_guest_path(guest), :class => "btn btn-sm btn-default" %> <%= link_to 'Destroy', guest, method: :delete, data: { confirm: 'Are you sure?' }, :class => "btn btn-sm btn-danger" %></td>
</tr>
<% end %>
</tbody>
</table>

The problem comes because a param without a value will be equal to "" which is still true in Ruby, so basically if your search_phone is ever empty then you'll see all the results because if params[:search_phone] will be true and so that block will be run, and the eventual code that's run will be equivalent to:
#guests = Guest.where( "phone like '%%'" )
Which is just two wildcards, and will therefore return all results. Other people have already mentioned changing that conditional to use .present? so it won't be run if it's blank.
You also asked about refactoring the code, I would write it like so:
controller
def index
#guests = Guest.search_or_all params
end
model
def self.search_or_all params={}
query = %i[first_name last_name email phone].map do |k|
kk = "search_#{k}"
sanitize_sql ["#{k} LIKE '%s'", "%#{params[kk]}%"] if params[kk]
end.compact.join " OR "
where query
end

Without going deep into a code refactoring. Try adding params[:field_name].present? to all the if statements.

You should put "^#{query}" to make this work as a regular expression.
This way your Guest.rb file will look like this
Guest.rb
def self.search_first_name(query)
# where(:email, query) -> This would return an exact match of the query
where("first_name like ?", "^#{query}")
end
def self.search_last_name(query)
# where(:email, query) -> This would return an exact match of the query
where("last_name like ?", "^#{query}")
end
def self.search_email(query)
# where(:email, query) -> This would return an exact match of the query
where("email like ?", "")
end
def self.search_phone(query)
# where(:email, query) -> This would return an exact match of the query
where("phone like ?", "%#{query}%")
end

Related

ElasticSearch Range Aggregation no output results with no error

Hello I've got this problem with the rails Elascticsearch range aggregations, it seems right as there's no error output but then again it also doesn't aggregate.
Heres my controller
def results
min_price = params[:min_price] if params[:min_price].present?
max_price = params[:max_price] if params[:max_price].present?
price_ranges = [{to: max_price}, {from: min_price, to: max_price}, {from: min_price}]
#results = Item.search(params[:q], aggs: {item_final_price: {ranges: price_ranges}}, page: params[:page], per_page: 10) if params[:q].present?
end
and my model
class Item < ApplicationRecord
include Elasticsearch::Model
include Elasticsearch::Model::Callbacks
# Item.import
searchkick callbacks: :async, highlight: [:item_name]
def search_data
{
item_name: item_name,
item_details: item_details,
item_final_price: item_final_price,
item_av_rating: item_av_rating
}
end
end
and my views
<%= form_tag results_path, method: :get, enforce_utf8: false, id: "q_filter" do %>
<section class="widget widget-categories">
<%= hidden_field_tag :q, params[:q] %>
<h3 class="widget-title">Price Range</h3>
<div class="form-group">
<label>Price Between</label>
<%= number_field_tag :min_price, params[:min_price], class: "form-control form-control-sm", placeholder: "Min Price" %>
</div>
<div class="form-group">
<label>And</label>
<%= number_field_tag :max_price, params[:max_price], class: "form-control form-control-sm", placeholder: "Max Price" %>
</div>
<%= button_tag(type: "submit", name: nil, class: "btn btn-outline-primary btn-sm btn-block") do %>
Filter Search
<% end %>
</section>
<% #results.each do |item| %>
<%= item.item_name %>
<% end %>
Try to target this in your view
#results.response["aggregations"]["item_final_price"]["buckets"]
If you're running in development, can you throw a binding.pry and see what the result keys are? The data should be there if the query returns results.

Two submission forms with form-tag on same page in rails

I have a weekly time entry form currently. How can i have another time entry form on the same page ? and these two forms need be submitted separately as different records. Any help would be appreciated .
Here is my code:-
show_weeks.html.erb
<div class="table-responisve>
<% if #dates != nil %>
<table class="table-bordered">
<thead>
<tr>
<% #dates.each do |date| %>
<th><%=date.to_s+","+date.strftime("%A").to_s %> </th>
<% end %>
</thead>
<tbody>
<tr>
<% #dates.each do |date| %>
<% if #time_entry %>
<td><%= text_field_tag "#{date}", #time_entry.hour_per_day["#{date}"], class: "dates" %></td>
<% else %>
<%if date < Date.today %>
<td> <%= text_field_tag "#{date}", "", class: "dates" %> </td>
<%else %>
<td><%= text_field_tag "#{date}", "", class: "dates" if date == Date.today && Time.now.strftime("%H").to_i >= 10 %> </td>
<% end %>
<% end %>
<% end %>
</tr>
<tr>
<% if #time_entry %>
<td colspan="2"> Please Enter your Comment </td>
<td colspan="5">
<% #time_entry.comments.each do |c| %>
<p><%= text_field_tag "Comment", c.message %> </p>
<% end %>
</td>
<%else%>
<td colspan="2"> Please Enter your Comment </td>
<td colspan="5"><%= text_field_tag "Comment", "" %>
</td>
<%end%>
</tr>
</tbody>
</table>
</div>
<button type="button" class="btn btn-primary"
id="save_entries">Submit</button>
<%= form_tag save_time_entries_path, method: 'post',
id:"save_time_entries" do %>
<%= hidden_field_tag "start_date", #dates.first%>
<%= hidden_field_tag "end_date", #dates.last%>
<%= hidden_field_tag "total_hours", "" %>
<%= hidden_field_tag "project_id", #project.id %>
<%= hidden_field_tag "time_entry", "" %>
<%= hidden_field_tag "message", "" %>
<% if #time_entry%>
<%= hidden_field_tag "time_entry_detail_id", #time_entry.id %>
<% end %>
<% end %>
<script>
$("#save_entries").click(function(){
var time_entry = []
var hours = 0;
var message = document.getElementById("Comment").value;
$('.dates').each(function() {
hours += Number($(this).val());
if ($(this).val() == 0)
{
time_entry.push($(this).attr('name'),0)
}else{
time_entry.push($(this).attr('name'),$(this).val())
}
});
if (hours > 60) {
alert("Total Hours Should be equal to 60");
return false;
}
else {
$("#message").val(message);
$("#time_entry").val(time_entry);
$("#total_hours").val(hours);
$("#save_time_entries").submit();
}
})
</script>
<%end%>
you can create 2 different forms with form_for, it shouldn't be a problem
I figure out solution. Using of two submission forms on same page is bad idea. So I have create previous weeks records by using after create call back and i given default values for TimeEntryDetail. Here it creates all weeks records in background. Suppose if you skipped for 6 weeks , it'll create 6 empty records in background. Here is my working code
Modal.rb
after_create :chceck_time
def check_time
#project_mem_check= ProjectMember.where(project_id: project, member_id: user).first.created_at
#present week dates coming here |
#time_entry_check = TimeEntryDetail.where(project_id: project, user_id: user).first.created_at
if #time_entry_check.nil?
#time_entry_check=#project_mem_check
end
#last_week_start=Date.today.beginning_of_week
#last_week_end =Date.today.end_of_week
#cheking project member creation shall be less than time entry creation of that project.
if #project_mem_check <= #time_entry_check
#time_check_first=TimeEntryDetail.where(project_id: project, user_id: user).pluck(:start_date).first.to_date
#time_check_last =TimeEntryDetail.where(project_id: project, user_id: user).pluck(:start_date).last.to_date
#check first entry == last time entry
if #time_check_first==#time_check_last
pm=ProjectMember.where(project_id: project, member_id: user).first.created_at.to_date
tm=Date.today.to_date
unfilled_weeks= ((tm-pm)/7).to_i+1
unfilled_weeks.times {
#last_week_start= #last_week_start-7
#last_week_end = #last_week_end-7
#call_back_entry=TimeEntryDetail.create(start_date: (#last_week_start).to_date, end_date: (#last_week_end).to_date,
project_id: project.id, user_id: user.id, hours: 0, aasm_state: "pending", hour_per_day: "" )
#call_back_entry.comments << Comment.create(message: "Please fill the timesheet ")
}
else
#Already this user have time entries and create empty records from where he stopped.
pm=created_at.to_date #--.present time entry is coming
tm=Date.today.to_date
unfilled_weeks= ((tm-pm)/7).to_i+1
unfilled_weeks.times{
#last_week_start= #last_week_start-7
#last_week_end = #last_week_end-7
#call_back_entry=TimeEntryDetail.create(start_date: (#last_week_start).to_date, end_date: (#last_week_end).to_date,
project_id: project.id, user_id: user.id, hours: 0, aasm_state: "submitted", hour_per_day: "" )
#call_back_entry.comments << Comment.create(message: "Not yet filled this week ")
}
end
end
end

Setting up pagination with will_paginate properly

I have been trying to setup pagination properly but I am having trouble following any tutorial and getting it to work properly.
What I basically want setup is that when a user chooses the number of companies they want to appear on a page, the following loop with paginate the given number of companies on each page. If the user doesn't choose a specific number of companies/page, there would be a default value that would be set.
If anyone could maybe give me a push in the right direction, that would be much appreciated.
View
<ul class="list-group">
<%= #comps.find_each do |comp| %>
<li class="list-group-item">
<div class="row">
<div class="span12">
<p style="font-size: 1.5em"><strong><%= link_to comp.name, comp %></strong></p>
<hr class="divider">
<div class="row">
<div class="span6">
<p><strong>Primary Field:</strong> <%= comp.primary_field %></p>
<p><strong>Description:</strong> <%= truncate(comp.description, length: 150) { link_to "Read More", comp, :target => "_blank"}%>
</p>
</div>
<div class="span5">
<% if signed_in? %>
<p><% if !(current_user.favorites.include? comp) %>
<%= link_to 'Favorite',
favorite_company_path(comp, type: "favorite"),
class: "btn btn-primary",
method: :put%>
<% else %>
<%= link_to 'Unfavorite',
favorite_company_path(comp, type: "unfavorite"),
class: "btn btn-danger",
method: :put%>
<% end %></p>
<% end %>
<p><strong>Website:</strong> <%= auto_link(comp.website, :html => { :target => '_blank' })%></p>
<p><strong>Location:</strong> <%= comp.address %></p>
</div>
</div>
</div>
</div>
</li>
<% end %>
<%= will_paginate #comps%>
</ul>
Controller (Where the list page is handled)
def filter
if ((params[:field] != "") and (params[:field] != "All Fields") and (params[:field] != nil))
# This will apply the filter
#comps = Company.where(primary_field: params[:field])
else
# This will return all records
#comps = Company.all
end
end
def list
#fields = ##primary_field
filter
#comps = #comps.paginate(:page => params[:page], :per_page => params[:number_of_companies] ||= 5)
end
Model for the list page
class DynamicPages < ActiveRecord::Base
self.per_page = 5
end
Since you are using will_paginate. You could do in this way.
Post.paginate(:page => params[:page], :per_page => params[:number_of_companies] ||= 10)
Here params[:number_of_companies] is the number of companies a user has selected and 10 is the
default page value.
class Post
self.per_page = 10
end
Also, your code snippet <%= #comps.find_each do |comp| %>, should be this <% %> instead of <%= %>

Cant get the Edit function Working

I have two models Employee and Overtime Definition The Associations are set like this
Employee
class Employee < ActiveRecord::Base
has_many :overtime_definitions
Overtime Definition
class OvertimeDefinition < ActiveRecord::Base
belongs_to :employee
I created an Overtime definition for an employee and it all looks fine.However I'm having trouble with editing the same for an employee.
overtime_definitions__controller:
def new
#flag = params[:flag]
#employee = Employee.find(params[:id])
#overtime = OvertimeDefinition.new
end
def create
#employee = Employee.find(params[:overtime_definition][:employee_id])
#overtime = OvertimeDefinition.new(params[:overtime_definition])
if (params[:half_day_extra_duty_hours][:hour].to_s !="" || params[:half_day_extra_duty_hours][:minute].to_s !="")
#overtime.half_day_extra_duty_hours = params[:half_day_extra_duty_hours][:hour].to_s + ":" + params[:half_day_extra_duty_hours][:minute].to_s + ":" + "00"
else
#overtime.half_day_extra_duty_hours = nil
end
if (params[:full_day_extra_duty_hours][:hour].to_s !="" || params[:full_day_extra_duty_hours][:minute].to_s !="")
#overtime.full_day_extra_duty_hours = params[:full_day_extra_duty_hours][:hour].to_s + ":" + params[:full_day_extra_duty_hours][:minute].to_s + ":" + "00"
else
#overtime.full_day_extra_duty_hours = nil
end
if #overtime.save
flash[:notice] = "Overtime Successfully Created for #{#employee.name}"
redirect_to :action => 'search_overtime'
end
end
def edit
#flag = params[:flag]
#overtime = OvertimeDefinition.find(params[:id][:employee_id])
#employee = Employee.find(params[:id])
end
def update
#employee = Employee.find(params[:id])
#overtime = OvertimeDefinition.find(params[:id])
if #overtime.update_attributes(params[:overtime_definition])
flash[:notice] = "Overtime Successfully Updated for #{#employee.name}"
redirect_to :action => 'search_overtime'
else
render :action => 'edit',:flag=>params[:flag]
end
end
Tried with these in the edit method
#overtime = OvertimeDefinition.find(params[:id][:employee_id])
#gives me can't convert Symbol into Integer error.
#overtime = OvertimeDefinition.find(params[:id])
#gives me Couldn't find OvertimeDefinition with ID=1353 error.Actually 1353 is the id of that employee.
3.#overtime = OvertimeDefinition.find(params[:employee_id])
#gives me couldn't find OvertimeDefinition without an ID error.
My _search_overtime_employee_list having these links for new and edit actions
<%=link_to "Calculation" ,:action => "new",:id=>employee.id, :flag=>"Calculation" %>
<%= link_to "Re-Calculate",:action => "edit",:id=>employee.id,:flag=>"Re-Calculate" %>
new.rhtml
<%= form_tag :action => 'create' do %>
<%= render :partial =>'form'%>
<center>
<%= submit_tag "Save",:onclick=>"return validate()",:class=>"buttons"%>
</center>
<% end %>
<%= link_to "Back" ,:action => "search_overtime" %>
edit.rhtml
<%= form_tag :action => 'update', :id=>#employee.id,:flag=> params[:flag],:value=>params[:id] %>
<%= render :partial =>'form'%>
<center>
<%= submit_tag "Update",:onclick=>"return validate()",:class=>"buttons"%>
</center>
<%= link_to "Back" ,:action => "search_overtime" %>
_form.rhtml
Employee Details
<table cellspacing="5">
<tr>
<td><b>Employee Code</b></td>
<%= hidden_field 'overtime_definition','employee_id',:value=>params[:id] %>
<td><%= #employee.employeeid %></td>
<td><b>Employee Name</b></td>
<td><%= #employee.personnel.display_full_name %></td>
</tr>
<tr>
<td><b>Department</b></td>
<td><%= #employee.department ? #employee.department.name : "" %></td>
<td><b>Designation</b></td>
<td><%= #employee.designation ? #employee.designation.name : "" %></td>
<td><b>Location</b></td>
<td><%= #employee.location.name%></td>
</tr>
</table>
</br>
<fieldset>
<table cellspacing="5">
<%= form_for :overtime_definition, :builder => LabelFormBuilder do |od| %>
<tr>
<td>
<label for="half_day_extra_duty_hours">
Half Day Extra Duty Hours
</label>
</td>
<td class ="datefamily">
<%= select_time(#overtime.half_day_extra_duty_hours, {:include_blank => true, :time_separator => ":",:prefix => "half_day_extra_duty_hours"})%>
</td>
</tr>
<tr>
<td>
<label for="full_day_extra_duty_hours">
Full Day Extra Duty Hours
</label>
</td>
<td class ="datefamily">
<%= select_time(#overtime.full_day_extra_duty_hours, {:include_blank => true, :time_separator => ":",:prefix => "full_day_extra_duty_hours"})%>
</td>
</tr>
<tr>
<%= od.sr_check_box :is_salary_basis, {}, true, false, :label => "Is Salary Basis"%>
</tr>
<tr>
<%= od.sr_check_box :is_fixed_amount, {}, true, false, :label => "Is Fixed Amount"%>
<td colspan="2" id="ov_hm" style="display: none">
Half Day Amount
<%= od.text_field :half_day_amount, :onkeypress => "return numbersonly(event)", :style => "width:40px" %>
</td>
<td colspan="2" id="ov_fm" style="display: none">
Full Day Amount
<%= od.text_field :full_day_amount, :onkeypress => "return numbersonly(event)", :style => "width:40px" %>
</td>
</tr>
<%end%>
</table>
I just lost out here completely in getting that edit action work.Any help is greatly appreciated!
Your current edit link is:
<%= link_to "Re-Calculate",:action => "edit",:id=>employee.id,:flag=>"Re-Calculate" %>
In your edit action:
#overtime = OvertimeDefinition.find(params[:id][:employee_id]) ## gives me can't convert Symbol into Integer error.
As per the edit link, you are directly passing :id in query params which you can access as params[:id]. There is no params[:id][:employee_id] in your params hash so when you say params[:id][:employee_id] Ruby tries to convert :employee_id to an integer which is a symbol. Hence, the error.
I think you should be passing id of OvertimeDefinition record in :id from your link. And access it as
#overtime = OvertimeDefinition.find(params[:id])
in the Controller's action.
#overtime = OvertimeDefinition.find(params[:id]) ## gives me Couldn't
find OvertimeDefinition with ID=1353 error.Actually 1353 is the id of
that employee.
This is because you are passing employee id in params[:id] so obviously this will not work. You need to pass OvertimeDefinition id here.
#overtime = OvertimeDefinition.find(params[:employee_id]) ## gives me
couldn't find OvertimeDefinition without an ID error.
You are not passing any :employee_id in query params within edit link. So, params[:employee_id] will be nil and find method fails because you didn't pass any id to it.
Solution :
Update your edit link as below:
<%= link_to "Re-Calculate",:action => "edit",:id=> #overtimedefinition.id , :employee_id => employee.id,:flag=>"Re-Calculate" %>
Replace #overtimedefinition.id with appropriate id of OvertimeDefinition record. As you have not shared the code, I don't know the name of OvertimeDefinition variable.
Update your edit action as:
def edit
#flag = params[:flag]
#overtime = OvertimeDefinition.find(params[:id])
#employee = Employee.find(params[:employee_id])
end

Pagination not working correctly in rails

I am trying to use will_paginate for a list of items I want to display.
There is a form with drop down selections to fetch objects by status.
This is my controller
def list
#person = Person.find_by_id(session[:person_id])
params[:status] = params[:redirect_status] if params.has_key?('redirect_status')
#statuses = Peptide.statuses
#status = 'Not Ordered'
#status = params[:status] if params[:status] != nil || params[:status] == ''
#peptides = Peptide.find(:all, :conditions => ['status = ?', #status]).paginate(:per_page => 30, :page => params[:page])
if Peptide.count.zero?
flash[:notice] = "There are not any peptides entered"
redirect_to :action => 'new'
end#if zero
end
This is in the view
<form action="/peptide/create_spreadsheet_of_not_ordered" enctype="multipart/form-data" method="post">
<table class="sortable" cellpading="5" cellspacing="2" width="100">
<tr class= "header-line">
<th>SS</th>
<th>Status</th>
<th>Peptide</th>
<th>Gene</th>
<th>Submitter</th>
<th>Created</th>
<th>Updated</th>
<th>Sequence</th>
<th>Modification</th>
<th>Vendor</th>
</tr>
<% for #peptide in #peptides.reverse %>
<tr valign = "top" class= "<%= cycle('color_one', 'color_two') %>">
<!--an error here during development likely indicates that the people table has not be repopulated or
that no submitter primer is present for a primer-->
<td sorttable_customkey = 0 > <%=check_box_tag "box[]", #peptide.id %>
<td><%= #peptide.status%></td>
<td class><%= link_to #peptide.name, :action => :report, :id => #peptide.id %></td>
<td><%= gene_links(#peptide.genes) rescue 'Error'%></td>
<td><%= #peptide.submitter.name rescue "" %></td>
<td <%= sorttable_customkey_from_date(#peptide.created_at)%> >
<%= #peptide.created_at.strftime("%b %d %Y") rescue "Unknown"%>
</td>
<td <%= sorttable_customkey_from_date(#peptide.updated_at)%> >
<%= #peptide.updated_at.strftime("%b %d %Y") rescue "Unknown"%>
</td>
<td><%= #peptide.sequence%></td>
<td><%= #peptide.modifications%></td>
<td><%= #peptide.vendor%></td>
<%= buttons() %>
</tr>
<%end%>
<%= will_paginate #peptides %>
</table>
<br>
<%= submit_tag "Create Spreadsheet"%>
The default list is grouped by status ordered.
however when I select any other status and submit the form the pagination links take me back to the default status.
Please help me resolve this issue.
Thanks
Without seeing the view, it sounds like you need to add the current params as an argument to the links for the other statuses...
Update
Try adding the params to your status link:
<%= link_to #peptide.name, peptide_path(#peptide, params), :action => :report, :id => #peptide.id %>
The documentation is here.

Resources