Using each_slice to produce a table but with sub headings - ruby-on-rails

I am using each_slice to output a two column table.
I would like to insert a title row when an attribute of the elements I am iterating changes.
I have :
all_users = Users.order('category, name asc').all
all_users.each_slice(2) do |two_users|
<tr>
<td style="text-align:right">
<%= two_users[0].category + ' - ' + two_users[0].name %>
</td>
<% if two_users[1].present? %>
<td>
<%= two_users[1].category + ' - ' + two_users[1].name %>
</td>
<td>
<% else %>
<td></td>
<% end %>
</tr>
<% end %>
And would like something like :
current_category = ''
all_users = Users.order('category, name asc').all
all_users.each_slice(2) do |two_users|
<% if two_users[0].category != current_category
current_category = two_users[0].category
%>
<tr><td colspan="2"><%= two_users[0].category %></td></tr>
<% end %>
<tr>
<td style="text-align:right">
<%= two_users[0].name %>
</td>
<% if two_users[1].present? %>
<td>
<%= two_users[1].name %>
</td>
<td>
<% else %>
<td></td>
<% end %>
</tr>
<% end %>
This doesn't work obviously in the case that two_users[1] has a new category.
I am trying to avoid the additional SQL queries of iterating through each category and requesting
the users for each independantly.

all_users.each_slice(2).with_object({cc: nil}) do |two_users, memo|
if category = two_users.detect { |u| u.category != memo[:cc] }
# print additional row or do whatever here
memo[:cc] = category
end
end
Enumerable#detect here returns either changed category or nil if there were no changes.
Sidenote: Try to DRY:
<td>
<%= two_users[1].name if two_users[1].present? %>
</td>

Related

need to save the checkbox value to other table in rails4 using fields_for.

this is the view page.---here using fields for method i'm passing data to JobPosting controller from check_box, Check box data need to be save in JobAssignment table.
<%- if #leads.present? -%>
<%= f.fields_for :assign do |x| %>
<%- #leads.each do |client| -%>
<% #requiter=UserRecruiter.where("reporting_to = ?", client.id)%>
<div class="col-md-3">
<table class="table table-bordered table-striped ">
<thead >
<tr class="bg-primary">
<th>
<%= x.check_box :assign_to, {}, client.id %>
<%= "#{client.first_name} #{client.last_name}" %>
</th>
</tr>
</thead>
<tbody style="height:110px">
<%- if #requiter.present? -%>
<%- #requiter.each do |req| -%>
<tr>
<td>
<%= "#{req.first_name} #{req.last_name}" %>
</td>
</tr>
<%end%>
<%end%>
</tbody>
</table> </div>
<%end%><%end%>
<%end%>
in controller---
def params_value
params.require(:job_posting).permit(:title, :description,:assign [])
end
def add_or_update_users
if params[:job_posting][:assign].present? && params[:job_posting] [:assign][:assign_to].present?
assign = params[:job_posting][:assign][:assign_to]
assign.each do |x|
#job.job_assignment = JobAssignment.where({ job_posting_id: #job.id, user_id: x }).first_or_create
#job.save
end
end
end
data is not saving to JobAssignment table.can any one tell me where i am doing wrong???
You can use build
def new
#jobpos = JobPosting.new
#jobpos.jobassignment.build
end
and replace the :assign to :jobassignment

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!

Rails loop with heading

I have this loop in Rails and I want to list each associated region_id under each region.name. So far under each region.name I get a list of all items.
Region has_many :trials
Trials belongs_to :region, :primary_key => 'region_id'
View
<% #regions.each do |region, list| %>
<h3><%= region.region.name %></h3>
<table class="table">
<% list.each do |list| %>
<tr>
<td>
<%= link_to list.site.site_name, trial_trials_path(trial_id: list.trial_id) unless list.site.site_name.blank? %>
</td>
<td>
<%= link_to list.trial_type, trial_trials_path(trial_id: list.trial_id) unless list.trial_type.blank? %>
</td>
<td>
<%= link_to list.grower.name, trial_trials_path(trial_id: list.trial_id) unless list.grower.name.blank? %>
</td>
</tr>
<% end %>
</table>
<% end %>
</div>
Controller
def index
list = Trial.where('year = ?', Time.now.year).order(:region_id)
#regions = list.group_by { |t| t.region_id }
end
In your controller, you have to group your items by region, using group_by added to your where close
In your view, you can then iterate through your items with #list[region].each

Resources