Rails loop with heading - ruby-on-rails

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

Related

ror How can i order by has many value

How can I order by has-many value
I want to do something like #cases = #user.cases.order_by(step.name="shipped" desc)
I have cases table and I want if the case.step.name = "Shipped" to be at the end of the table
I have case model
has_many :steptations, dependent: :destroy
has_many :steps, through: :steptations
accepts_nested_attributes_for :steps
and step model
has_many :steptations,dependent: :destroy
has_many :cases, through: :steptations
Here is my cases controller
def index
#cases = #user.cases.all
end
Here is my case.html
<% #cases.each do |item| %><tr>
<td ><%= link_to case_path(item) do %><%= item.number %><% end %></td>
<% if item.steptations.present? %>
<% item.steptations.where(:status=>true).each do |t| %>
<% if t.step&.id == 13 %>
<td class= 'fa fa-circle red' ></td>
<% elsif item.finished == true && t.step&.name == "Shipped"%>
<td class= 'fa fa-circle red' ></td>
<% elsif item.finished == true %>
<td class= 'fa fa-circle dark'></td>
<% else %>
<td class= 'fa fa-circle green'></td>
<% end %>
<% end %>
<% else %>
<td>0</td>
<% end %>
<td> <%= link_to case_path(item) do %><%= item.pt_first_name.capitalize %> <%= item.pt_last_name.capitalize %><% end %></td>
<td><%=link_to item.user.full_name,doctor_path(item.user)%></td>
<td> <%= item.date_received.strftime("%b-%-d-%-y") %></td>
<td> <%= item.due_date.strftime("%b-%-d-%-y") %></td>
<td><%= item.shade %></td>
<td><%= item.mould %></td>
<td><%= item.upper_lower %></td>
<% if item.steptations.present? %>
<% item.steptations.where(:status=>true).each do |t| %>
<% if t.step&.name == "Conversion" %>
<td class="red"><%= t.step&.name%></td>
<% else %>
<td><%= t.step&.name%> </td>
<% end %>
<% end %>
<% else %>
<td>0</td>
<% end %>
</td>
</tr>
<% end %></tbody>
</table><br>
What you're looking for is the SQL ORDER BY FIELD function. In Ruby it should be something like this:
Case.where(user: #user).order("FIELD(name, #{some name param variable}) desc")
Try this:
Case.joins(steptations: :step)
.group("cases.id")
.select("cases.*,
COUNT(steps.name) filter (where steps.name = 'shipped') as shipped")
.order(:shipped)

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

Using each_slice to produce a table but with sub headings

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>

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

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!

Resources