Rails search function rendering page multiple timess - ruby-on-rails

I have a search function in rails that should render a page to display the grants that were picked up by the search. However when you search, the template is rendered multiple times instead of just once, and its rendered on top of itself so it looks like a cluttered mess. I'm not sure where the error is but it must be calling render more than once. Heres my controller method:
def index
if params[:search]
#grants = Grant.search(params[:search]).order("created_at DESC")
else
#grants = Grant.all.order('created_at DESC')
end
end
And the part of my view where I render the template
<% if #grants.present? %>
<%= render #grants %>
<% else %>
<p>There are no grants containing the term(s) <%= params[:search] %>.</p>
<% end %>
<%= yield %>
and the template;
<html>
<body>
<style>div {
margin-left:17%;
padding:1px 16px;
height:1000px;}
</style>
<div>
<center>
<hr style="height:5 px; visibility:hidden;" />
<br>
<font size=6 >
<strong>
US Federal Grants
<br>
<br>
<hr style="height:5 px; visibility:hidden;" />
</strong>
</font>
</center>
<% if #grants != [] && #grants != nil%>
<table border="1" style="width:100%">
<tr>
<td><strong><font size=5>Title</font></strong></td>
<td><strong><font size=5>Award Ceiling</font></strong></td>
<td><strong><font size=5>Description</font></strong></td>
<td><strong><font size=5>Additional Information</font></strong></td>
<td><strong><font size=5>Closing Date</font></strong></td>
</tr>
<% for item in #grants %>
<tr>
<td><%= item.title %></td>
<% if item.ceiling != '$0' && item.ceiling != nil && item.ceiling != '' && item.ceiling != '$1' && item.ceiling != '$2'%>
<td><%= item.ceiling %></td>
<% else %>
<td> See link for more information </td>
<% end %>
<% if item.description == "" %>
<td>See link for more information</td>
<%elsif item.description == nil%>
<td>See link for more information</td>
<% elsif item.description.sub('Description:', '').length > 720 %>
<td>
<%= truncate(item.description.sub('Description:', ''), length: 720) %>
<%= link_to 'Read more', '', class: "read-more-#{item.id}" %>
<script>
$('.read-more-<%= item.id %>').on('click', function(e) {
e.preventDefault()
$(this).parent().html('<%= escape_javascript item.description.sub('Description:', '') %>')
})
</script>
</td>
<%else%>
<td> <%=item.description.sub('Description:', '')%></td>
<%end%>
<td><center> <a href= <%= item.link %>>LINK</a><center></td>
<%unless item.date == nil%>
<td><% newdate = Date.parse item.date %>
<%= newdate.strftime("%D") %>
</td>
<%end%>
</tr>
<% end %>
<% else %>
<center>
<p> There are no Grants available to Entrepreneurs in this category at this time. However this list updates daily based on Grants.gov data, so feel free to check back later. </p>
</center>
<% end %>
</table>
</div>
</body>
</html>
I'm not sure where its happening but it seems to be rendering it about 25 times

You've accidentally encountered Rails collection rendering. You can read more about it here: https://robots.thoughtbot.com/rendering-collections-in-rails
When you do
<%= render #grants %>
Rails interprets this as you wanting to render the grants/_grant.html.erb (I think – or some similar path) partial once for each grant.
If you instead want to render it only once, try
<%= render "grants/grant" %>
(Renaming the partial to something like "_grants.html.erb" and rendering that might also be a good idea, just so it doesn't look like it's intended to render a single grant.)

Related

How to check if association exists and display associated record instead of actual record.

I am trying to have the system check to see if there is a customer category, if there is, display the customer category and if not display the internal category. I tried doing something like
<% if c.customer_labor_category != 'nil' %>
I also tried the following right above where it displays "l"
<% if c.customer_labor_category.any? %>
I basically need it to check if there is a customer category if there is, use that field instead of the internal one.
<% c = lh.pluck('categories.category').uniq %>
<% if c.length == 0 %>
<tr>
<td class="tg-multirow" rowspan="1">Category</td>
<td class="tg-datacell"></td>
<td class="tg-celltitle" rowspan="1">Effort</td>
<td class="tg-datacell"></td>
</tr>
<% else %>
<% c.each do |l| %>
<tr>
<% if l == c.first %>
<td class="tg-celltitle" rowspan="<%= lc.length %>">Labor Category</td>
<% end %>
<td class="tg-datacell"> <%= l %> </td>
<% if l == c.first %>
<td class="tg-celltitle" rowspan="<%= c.length %>">effort</td>
<% end %>
<% hours = lh.joins(:category).where(:categories => { :category => l }).each.sum(&:hours) %>
<td class="tg-datacell"> <%= hours %></td>
</tr>
<% end %>
<% end %>
c.customer_labor_category.nil? # true if nil
c.customer_labor_category.present? # true if not nil

Format Active Record Data before rendering as JSON

I have a data table that i am going to convert to Ajax and have to format the JSON values into the right formats.
In this example how would i format the tables.created_at time-stamp to MM/DD
format...
tables = Table.where(:state => "Missouri")
respond_to do |format|
format.json { render json: tables }
end
In the DOM i would do a loop through the data and do this where i needed it: Chronic.parse(s.created_at.to_date).strftime("%m/%d")
And as you can see i have alot of additional formatting to do to the data before it is returned as JSON:
<% if #load_search.nil? %>
<tr></tr>
<% else %>
<% #load_search.each do |s| %>
<tr id="row_<%= s.id %>">
<td align="center">
<%= s.id %>
</td>
<td class="count" align="center">
<%= s.results %>
</td>
<td align="center">
<%= Chronic.parse(s.created_at.to_date).strftime("%m/%d") %>
</td>
<td align="center">
<% if s.equipment.empty? %>
All Equipment
<% else %>
<%= s.equipment.pluck(:code).to_s.gsub("[","").gsub(']','').gsub('"','') %>
<% end %>
</td>
<td align="center">
<% if s.origin_id.nil? %>
<%= s.origin_states %>
<% else %>
<%= Location.find(s.origin_id).cs unless s.origin_id.nil? %>
<% end %>
</td>
<td align="center">
<%= s.origin_radius_cs %>
</td>
<td align="center">
<% if s.dest_id.nil? %>
<%= s.dest_states %>
<% else %>
<%= Location.find(s.dest_id).cs unless s.dest_id.nil? %>
<% end %>
</td>
<td align="center">
<%= s.dest_radius_cs %>
</td>
<td align="center">
<%= s.length.to_s + ' ft.' unless s.length.nil? %>
</td>
<td align="center">
<%= s.weight.to_s + ',000 lbs' unless s.weight.nil? %>
</td>
<td align="center">
<% if s.ltl %>
Partial
<% elsif s.both %>
Full
<% else %>
Both
<% end %>
</td>
<td align="center">
<%= Chronic.parse(s.pickup.to_date).strftime("%m/%d") %>
</td>
<td align="center">
<%= Chronic.parse(s.delivery.to_date).strftime("%m/%d") unless s.delivery.nil?%>
</td>
</tr>
<% end %>
<% end %>
You can override the ActiveRecord getter as
class Model
def created_at
self[:created_at].strftime("%m/%d")
end
end

Random selection from Rails database works on Index, not on its 'Generator page'

I'm writing what's currently a very basic program (and I'm sure very badly-coded, though kinda working) to generate fitness plans, currently split by bodypart or through a generator that selects an item from each bodypart.
I'm having problems with the workout generator though - it works on the index page for testing purposes, with a new workout every time it's refreshed, though on the '/exercises/generator' page where it should live, it will load the index's random workout but not a new plan when refreshed. Looking for a solution to get it working as a standalone generator on this page.
I'm new to this, and have worked to get the program running with what I'm sure is very messy scope and code I'd love to get dryer, so bonus points for tips on correcting this!
If any of the above is unclear, let me know - here's the relevant code from the controller, index.html.erb and bodypart.html.erb (where the generator will sit), along with a partial sitting on the view pages. If there's anything else that would help - shout me.
Controller (less the standard CRUD info)
class ExercisesController < ApplicationController
private
def exercise_params
params.require(:exercise).permit(:move, :bodypart)
end
public
attr_accessor :move, :bodypart
def index
#exercise = Exercise.new
#exercises = Exercise.all
$gen = Exercise.pluck(:move, :bodypart)
$gen.shuffle!
$generatorl = $gen.select { |a, b| b == "legs" } #feel b.downcase should work to grab capitalized :bodyparts, though not working for now
$generatorl = $generatorl.first
$generatorb = $gen.select { |a, b| b == "back" }
$generatorb = $generatorb.first
$generators = $gen.select { |a, b| b == "stomach" }
$generators = $generators.first
$generatorsh = $gen.select { |a, b| b == "shoulders" }
$generatorsh = $generatorsh.first
$generatorc = $gen.select { |a, b| b == "chest" }
$generatorc = $generatorc.first
$generator = $generatorl, $generatorb, $generators, $generatorsh, $generatorc
$generator.shuffle!
end
def bodypart
#fullpath = request.fullpath
bp = if #fullpath == '/exercises/legs'
'legs'
elsif #fullpath == '/exercises/full'
'full'
elsif #fullpath =='/exercises/shoulders'
'shoulders'
elsif #fullpath == '/exercises/back'
'back'
elsif #fullpath == '/exercises/chest'
'chest'
elsif #fullpath == '/exercises/stomach'
'stomach'
elsif #fullpath == '/exercises/generator'
'generator'
else
'error'
end
#exercises = if bp == 'error'
redirect_to exercises_path
else
Exercise.where(:bodypart => bp)
end
end
(Definitely got the right amount of 'ends' in the real code, in case I've misquoted here)
And the views:
Index
<h1>Exercises</h1>
<p></p>
<%= render 'table' %>
<h2> Workout Generator </h2>
<p> <%= $gen.inspect %> </p>
<p> <%= $generator.inspect %> </p>
<p> <%= $generatorl.inspect %> </p>
<table border="1">
<tr>
<th><%= "Exercise" %></th>
<th><%= "Body part" %></th>
</tr>
<% $generator.each do |mv, bp| %>
<tr>
<td> <%= mv.titleize %> </td>
<td><i> <%= bp.titleize %> </i></td>
</tr>
<% end %>
</table>
The view for each bodypart / the generator:
<h1>
<% if #fullpath == '/exercises/generator' %>
<%= 'Generator' %>
<% else %>
<%= :bodypart.to_s.titleize %></h1>
<% end %>
<h2> Test <%= $fullpath.inspect %> <%= request.fullpath %> </h2>
<% if #exercises.empty? %>
<p> <%= $gen %> </p>
<p> <%= $generator %> </p>
<table border="1">
<tr>
<th><%= "Exercise" %></th>
<th><%= "Body part" %></th>
</tr>
<% $generator.each do |mv, bp| %>
<tr>
<td> <%= mv.titleize %> </td>
<td><i> <%= bp.titleize %> </i></td>
</tr>
<% end %>
</table>
<% else %>
<%= render 'table' %>
<table>
<tr>
<td> <%= #exercises.inspect %> </td>
</tr>
</table>
<% end %>
And finally the partial for Table:
<table border="1">
<tr>
<th><%= "Exercise" %></th>
<th><%= "Body part" %></th>
</tr>
<% for exercise in #exercises %>
<tr id="exercise_<%= exercise.id %>">
<td> <%= exercise.move.titleize %> </td>
<td><i> <%= exercise.bodypart.titleize %> </i></td>
<td> <%= link_to "Edit", edit_exercise_path(exercise) %> </td>
<td> <%= button_to 'Delete', exercise, :method => :delete %> </td>
</tr>
<% end %>
</table>
Thanks so much in advance - if I'm being unclear or any other code would be useful, let me know!

advanced Search (checkboxes and selection)

I'm having a problem with my advanced search.
Essentially, its an advanced search for bands (name, style, bandpicture by checkboxes (checked: have a bandpicture))
Here is the code.
result.html.erb
<table >
<colgroup>
<col width="250" />
</colgroup>
<tr>
<td>
<label for="name">Filter</label></br>
<%= form_tag band_path do %>
<label for="Style">Style</label></br>
<%= select_tag :style_id, options_from_collection_for_select(Style.all, :id, :name, params[:style_id]), include_blank: true, class: "form-control" %>
<br>
</br>
<%= check_box_tag 'options[]', "picture" %>
<%= button_to '#', class: 'btn btn-default' do %>
<%= t(:find) %>
<% end %>
<% end %>
</td>
<td>
<div>
<% #bands.each do |band|%>
<div class="top-bar">
<div class="center">
<div class="info">
<div class="name"><%=band.id %></div>
<div> <%= band.zip %>, <%= band.city %> </div>
</div>
<div class="desc">
<table>
<tr>
<td>Styles</td>
<td>
<% band.styles.each do |s| %>
<%= s.style.name %>
<% end %>
</td>
</tr>
</table>
</div>
<% end %>
</td>
</tr>
</table>
models band.rb
def self.search1(style_id)
Profile.joins("...").where("style_id = ?", style_id)
end
controller.
def searchresult
if params[:style_id].present?
#bands = Band.search1 params[:style_id]
elsif params[:options]
Band.where(:options => #filtered_options)
else
#bands = Band.all
end
end
The searchresult don't show the result of the checkboxes and I have this errors:
undefined method `search1' for #<Class:0x00000008eb5548>

getting textfield value and search result after page after click on search button in ruby on rails

In my search page I have a textfield of zip code and when I enter Zip code in the textfield and click on search button the value of text field is loss and also search result is loss, what I do to stable textfield value of zip code and search result after click on search button. below is my view page:
<%= form_for :search, :url => { :method => :get, :action => :search } do |f| %>
<table width="100%">
<tr>
<td align="center" style="vertical-align:top;" width="35%">
<table>
<tr>
<td align="center">
<%= text_field_tag "tf_Zip",nil,:placeholder =>'Zip' %>
</td>
</tr>
</table>
<table>
<% if !#user.nil? %>
<% #user.each do |uzr| %>
<tr>
<td bgcolor="#CCDBE0" width="40%">
<%= image_tag #user_img.photo.url(:small),:alt => " " %>
<br/>
<div><a style="color:blue;" href = 'profile?id=<%= uzr.id %>'><%= uzr.First_Name + " " + uzr.Last_Name %></a></div>
</td>
<td bgcolor="#CCDBE0" width="60%" style="text-align:center;">
<div class='buttonblck1'><a href='searchings?id=<%= uzr.id %>'>Send Request </a></div>
</td>
</tr>
<% end %>
<% end %>
</table>
<% end %>
and below is controller page
if ( !params[:tf_Zip].blank? or params[:tf_Zip] != "" )
#user = User.find(:all,:conditions=>['"user_Zip" = ? and "id" != ? ',params[:tf_Zip], current_user.id])
end
Kindly suggest me, waiting for your reply.'
Thanks
First:
form_for is meant to be used with an instance of ActiveModel or ActiveRecord.
Use form_tag, if you want to create a form, that is not based on an object.
Second:
as you have not object, where the attributes are stored, you have to provide them yourself.
The value is defined in the second parameter of text_field_tag
i.e. in your controller:
#zip_search = params[:tf_Zip].presence
if #zip_search
#user = ...
end
and in your view:
<%= form_tag url_for( :controller => :search, :action => :search), :method => :get) do %>
<%= text_field_tag "tf_Zip", #zip_search, :placholder => 'Zip' %>
<% end %>

Resources