How to select data from multiple model in rails - ruby-on-rails

i have three model project_manager, project_director, and human_resource each has a status Boolean field how can i print some thing in rails if Boolean value of these three model is true. currently i am accessing data from model by doing this-
<% if project_site.project_managers.empty? %>
<td class="pending fi-eye"><%= " Pending" %></td>
<% else %>
<% project_site.project_managers.each do |project_manager| %>
<% if project_manager.status == false %>
<td class="rejected fi-x"><%= ' Rejected' %></td>
<% elsif project_manager.status == true %>
<td class="approved fi-check"><%= " Approved" %></td>
<% end %>
<% end %>
<% end %>
<% if project_site.project_directors.empty? %>
<td class="pending fi-eye"><%= " Pending" %></td>
<% else %>
<% project_site.project_directors.each do |project_director| %>
<% if project_director.status == false %>
<td class="rejected fi-x"><%= ' Rejected' %></td>
<% elsif project_director.status == true %>
<td class="approved fi-check"><%= " Approved" %></td>
<% end %>
<% end %>
<% end %>
<% if project_site.human_resources.empty? %>
<td class="pending fi-eye"><%= " Pending" %></td>
<% else %>
<% project_site.human_resources.each do |human_resource| %>
<% if human_resource.status == false %>
<td class="rejected fi-x"><%= ' Rejected' %></td>
<% elsif human_resource.status == true %>
<td class="approved fi-check"><%= " Approved" %></td>
<% end %>
<% end %>
<% end %>
i want to print approved if all these three model status value is true how can i do that in rails?

Create a helper method and put the following code :
def check_resource_status(project_site, resources)
statuses = project_site.send(resources.to_sym).pluck(:status)
statuses.all? ? true : false
end
def status_container(status)
content_tag :div, class: ['sample'] do
status_label = status ? 'Approved' : 'Rejected'
default_class = status ? 'fi-check' : 'fi-x'
status_class = [default_class, status_label.downcase]
concat content_tag(:label, status_label, class: status_class)
end
end
From your view file :
status_container(check_resource_status(project_site, 'human_resources'))
status_container(check_resource_status(project_site, 'project_directors'))
status_container(check_resource_status(project_site, 'project_managers'))

If I understood your question correctly, all you need is something like this:
<% if human_resource.status? %>
<td class="approved fi-check"><%= ' Approved' %></td>
<% else %>
<td class="rejected fi-x"><%= ' Rejected' %></td>
<% end %>

Related

Problems to update registry with ajax Rails

I'm updating a registry, but when the registry is updated, the row of the updated record is disorganized, here my code:
index.html.erb
<table id="enterprises-items">
<thead>
<tr>
<td>Nombre</td>
<td>Email</td>
<td>Categoria</td>
<td>Municipio</td>
<td class="text-left">...</td>
<td colspan="2">Opciones</td>
</tr>
</thead>
<tbody>
<% #enterprises.each do |enterprise| %>
<%= render partial: "enterprises/list", locals: { enterprise:enterprise } %>
<% end %>
</tbody>
</table>
update.js.erb
<% if #enterprise.errors.empty? %>
$('#exampleModal1').foundation('close');
$('#enterprise-<%= #enterprise.id %>').html("<%= escape_javascript(render partial: 'list', locals: { enterprise:#enterprise }) %>");
<% end %>
_list.html.erb
<tr id="enterprise-<%= enterprise.id %>">
<td><% if enterprise.name.blank? %>No disponible<% else %><%= truncate(enterprise.name, length: 30) %><% end %></td>
<td><% if enterprise.email.blank? %>No disponible<% else %><%= truncate(enterprise.email, length: 30) %><% end %></td>
<td><% if enterprise.enterprise_tag_id.blank? %>No disponible<% else %><%= truncate(enterprise.enterprise_tag_id, length: 10) %><% end %></td>
<td><% if enterprise.municipality_id.blank? %>No disponible<% else %><%= truncate(enterprise.municipality_id, length: 15) %><% end %></td>
<td class="text-left">...</td>
<td><%= link_to edit_enterprise_path(enterprise), remote: true, :data => { :open => 'exampleModal1' }, class: "button tiny green", id: "update_" do %><i class="fi-pencil"></i><% end %></td>
<td><%= link_to enterprise, method: :delete, data: { confirm: "¿Desea eliminar este registro?" }, remote: true, class: "button tiny red" do %><i class="fi-trash"></i><% end %></td>
</tr>
This is the solution =D
$("#enterprise-<%= #enterprise.id %>").replaceWith("<%= escape_javascript(render partial: 'list', locals: { enterprise:#enterprise }) %>");

Will_paginate with hash in Rails

I have controller looks like :
## controllers/lhgs_controller.rb
def index
#per_page = params[:per_page] || 10
#totalsolds = Totalsold.paginate(:per_page => #per_page, :page => params[:page]).order('date asc').group_by{ |s| [s.date, s.store_id, s.nomor] }
end
And views :
## index.hmtl.erb
<div id="totalsolds"><%= render 'totalsolds' %></div>
## views/_totalsolds.html.erb
<% #totalsolds.each do |(date, store, nomor), totalsold| %>
<tr>
<td><%= date.strftime("%d/%m/%Y") %></td>
<td><%= nomor %></td>
<td><%= Store.find(store).name %></td>
<% totalsold.each do |ts| %>
<td><%= ts.qty == 0 || ts.qty == nil ? "-" :prod.qty %></td>
<% end %>
<td>Rp<%= number_to_currency(totalsold.sum(&:value), :unit => "") %></td>
<td><%= link_to "edit", edit_bt_path(:store_id => store, :date => date, :nomor => nomor), :class => "btn btn-primer" %></td>
</tr>
<% end %>
...
...
<div class="row">
<div class="col-sm-6">
<% line 65 %>
<%= page_entries_info #totalsolds %>
</div>
<div class="col-sm-6">
<%= will_paginate #totalsolds, :style => 'float:right;margin-top:-5px;height:30px;' %>
</div>
</div>
I got an error :
ArgumentError in Lhgs#index
Showing C:/Sites/cms/app/views/lhgs/_totalsolds.html.erb where line
65 raised:
The #lhgs variable appears to be empty. Did you forget to pass the
collection object for will_paginate?
I found same question and solution, but I can't figure out how to use it for my case.
UPDATE :
I'm not found anywhere #lhgs variable, I tried to change #totalsolds to #lhgs and now my controller lookslike :
## controllers/lhgs_controller.rb
def index
#per_page = params[:per_page] || 10
#lhgs = Totalsold.order('date asc').group_by{ |s| [s.date, s.store_id, s.nomor] }
#lhgs = #lhgs.paginate(:per_page => #per_page, :page => params[:page])
end
And this an error :
NoMethodError in LhgsController#index
undefined method `paginate' for #<Hash:0x4c034a0>
Use rails console :
irb(main):001:0> #lhgs = Totalsold.order('date asc').group_by{ |s| [s.date, s.store_id, s.nomor] }
.... look at pastebin ......
irb(main):002:0> #lhgs.class
=> Hash
pastebin
Solved
reference
On controller :
def index
#per_page = params[:per_page] || 10
#lhgs = Totalsold.order('date asc').group_by{ |s| [s.date, s.store_id, s.nomor] }
#lhgs_keys = #lhgs.paginate(:per_page => #per_page, :page => params[:page])
end
And on view :
<% #lhgs_keys.each do |k| %>
<% #lhgs[k].group_by{ |s| [s.date, s.store_id, s.nomor] }.each |(date, store, nomor), totalsold| %>
.....
....
<% end %>
<% end %>
<div class="row">
<div class="col-sm-6">
<% line 65 %>
<%= page_entries_info #lhgs_keys %>
</div>
<div class="col-sm-6">
<%= will_paginate #lhgs_keys, :style => 'float:right;margin-top:-5px;height:30px;' %>
</div>
</div>
Try it like this:
# controllers/lhgs_controller.rb
def index
#per_page = params[:per_page] || 10
#totalsolds = Totalsold.paginate(:per_page => #per_page, :page => params[:page]).order('date asc').group_by{ |s| [s.date, s.store_id, s.nomor] }
respond_to do |format|
format.html
end
end
And the index.html can be like this:
<% #totalsolds.each do |(date, store, nomor), totalsold| %>
<tr>
<td><%= date.strftime("%d/%m/%Y") %></td>
<td><%= nomor %></td>
<td><%= Store.find(store).name %></td>
<% totalsold.each do |ts| %>
<td><%= ts.qty == 0 || ts.qty == nil ? "-" :prod.qty %></td>
<% end %>
<td>Rp<%= number_to_currency(totalsold.sum(&:value), :unit => "") %></td>
<td><%= link_to "edit", edit_bt_path(:store_id => store, :date => date, :nomor => nomor), :class => "btn btn-primer" %></td>
</tr>
<% end %>
...
<div class="row">
<div class="col-sm-6">
<% line 65 %>
<%= page_entries_info #totalsolds %>
</div>
<div class="col-sm-6">
<%= will_paginate #totalsolds, :style => 'float:right;margin-top:-5px;height:30px;' %>
</div>
</div>

How to use an if statement to filter records from a model object ror

I have service and servicebooking models, I want to view the current users made servicebookings by checking the owner_id attribute in the servicebooking model.
My servicebooking controller method:
def myservicebookings
if current_user.id == #servicebooking.owner_id
#servicebookings = current_user.servicebookings.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page])
else
"You have no service bookings"
end
end
My servicebookings view:
<% if current_user.id == #servicebooking.owner_id %><% #servicebookings.each do |servicebooking| %>
<tr>
<td><%= servicebooking.date %></td>
<td><%= servicebooking.time %></td>
<td><%= servicebooking.service_name %></td>
</tr>
<% end %>
<% else %>
<%= "You have no outgoing service bookings" %>
<% end %>
Currently I get the following error when trying to load the myservicebookings form:
undefined method `owner_id' for nil:NilClass
Any ideas on how to change this code to make it work? thanks in advance guys.
in you case, you dont need if statment because in this variable you have all current user servicebooking:
def myservicebookings
#servicebookings = current_user.servicebookings.
^^^^^^^^^^^^ search(params[:search]).
order(sort_column + " " + sort_direction).
paginate(:per_page => 5, :page => params[:page])
end
use this:
<% if #servicebookings.any? %>
<% #servicebookings.each do |servicebooking| %>
<tr>
<td><%= servicebooking.date %></td>
<td><%= servicebooking.time %></td>
<td><%= servicebooking.service_name %></td>
</tr>
<% end %>
<% else %>
<%= "You have no outgoing service bookings" %>
<% end %>
or this:
<% if #servicebookings.any? %>
<% for servicebooking in #servicebookings %>
<tr>
<td><%= servicebooking.date %></td>
<td><%= servicebooking.time %></td>
<td><%= servicebooking.service_name %></td>
</tr>
<% end if current_user.id == servicebooking.owner_id %>
<% else %>
<%= "You have no outgoing service bookings" %>
<% end %>
You should switch the position of the loop and and if statement in your view, then use the loop variableservicebooking not the instance variable #servicebooking, making it look like this
<% #servicebookings.each do |servicebooking| %>
<% if current_user.id == servicebooking.owner_id %>
the rest of the view ...
UPDATE: If you want to update on the controller level, then it's almost the same:
#servicebookings = current_user.servicebookings.search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 5, :page => params[:page])
#servicebookings.select! { |servicebooking| servicebooking.owner_id == current_user.id }
I would not mess with my views or my controller. I would go OOPS here. In RoR, its skinny controllers, fat models.
Goto your model,
class ServiceBooking < ActiveRecord::Base
# u = User, srch = params[:search],p = params[:page],p_p = per_page,s_c =sort_columns, s_d = sort_direction
def self.mine(u,srch,s_c,s_d,p,p_p = 5)
u.servicebookings.search(srch).order(s_c + " " + s_d).paginate(per_page: p_p, page: => p)
end
end
In your controller,
def myservicebookings
# 6th argument to this method is overridable.
#mine = ServiceBooking.mine(current_user,params[:search],sort_column,sort_direction,params[:page])
end
In your View,
<% #mine.each do |m| %>
<tr>
<td><%= m.date %></td>
<td><%= m.time %></td>
<td><%= m.service_name %></td>
</tr>
<% end %>

An Error when showing group_path(#group)

Now, I tried to set up the route with group_path(#group) but got an error message like,
ActiveRecord::RecordNotFound at /groups/%23%3CActiveRecord::Relation:0x007fd6cf362538%3E
Couldn't find Group with id=#<ActiveRecord::Relation:0x00fds6cf362538>
Here is my code. I would like to set up a link to groups/show/:id. Why did this error occur? Could you give me how to solve this?
☆index.html.erb
<% if #items.present? %>
<% #items.each do |i| %>
<% i_attr = i.get_element('ItemAttributes') %>
<tr>
<td> <%= link_to image_tag(i.get('SmallImage/URL'), {:style => 'border: none;'}), i_attr.get('DetailPageURL') %></td>
<td> <%= link_to i_attr.get('Title'), i_attr.get('DetailPageURL') %></td>
<td> <%= i_attr.get('Author') %></td>
<td> <%= i_attr.get('PublicationDate')%></td>
<td> <%= i_attr.get('Publisher') %></td>
<td> <%= i_attr.get('NumberOfPages')%></td>
<td>
<% if #existing_groups_isbns.include? i_attr.get('ISBN') %>
<% #existing_groups_isbns.each do |isbn| %>
<% if isbn == i_attr.get('ISBN') %>
<% #group = Group.where(:isbn =>isbn) %>
<%= link_to '既存ページへ' , group_path(#group) %>
<% end %>
<% end %>
<% else %><!-- if includes?==-->
<%= link_to '新規作成', {:controller => 'groups', :action => 'new', :name => i.get('ItemAttributes/Title'),:author => i.get('ItemAttributes/Author'), :publish => i.get('ItemAttributes/Publisher'), :published => i.get('ItemAttributes/PublicationDate'), :isbn => i.get('ItemAttributes/ISBN'), :page => i.get('ItemAttributes/NumberOfPages'), :imageurl=>i.get('MediumImage/URL')} ,class: "btn btn-midium btn-primary"%>
<% end %><!--if includes?-->
</td>
</tr>
<% end %><!-- #items.each do-->
<% else %><!--if #items.present?-->
見つかりませんでした。
<% end %><!-- if #items.present?-->
☆index_controller
def index
#keyword = params[:keyword]
if #keyword.present?
Amazon::Ecs.debug = true
res = Amazon::Ecs.item_search(params[:keyword],
:search_index => 'All', :response_group => 'Medium')
#items = res.items
search_isbns = #items.map{ |isbns| isbns.get('ItemAttributes/ISBN')}
search_asins = #items.map{ |asins| asins.get('ItemAttributes/ASIN')}
#existing_groups_isbns = Group.select(:isbn).where(:isbn => search_isbns).map(&:isbn)
#existing_groups_ids = Group.where(:isbn => search_isbns).map{|g| g.id}
end
Replace
<% #group = Group.where(:isbn =>isbn) %>
with
<% #group = Group.where(:isbn =>isbn).first %>
Because you need an object where you had an ActiveRecord relation

Updating table fields with button click

I'm trying to update cell in my table with the data from a drop down box in that row each time the button is clicked in that row. Each row has a drop down box and a button as you can see in this image:
http://i.imgur.com/eVJumuk.png
I'm trying to set it up so that when user selects a value from a drop down box and clicks the update button it will update value of Room column only for that row. But I can't figure out how to get the button even working and wanted to see if anyone can help me with this.
Here is my controller:
def index
#students = Student.all
#first_floor = %w(1101 1102 1103 1104 1105)
#second_floor = %w(2101 2102 2103 2104)
#third_floor = %w(3101 3102 3103 3104)
#selected_room = params[:room]
respond_to do |format|
format.html # index.html.erb
format.json { render json: #students }
end
end
Here is the part of the view for the table:
<% #students.each do |student|%>
<tr>
<td><%= student.id %></td>
<td><%= student.n_number %></td>
<td><%= student.f_name %></td>
<td><%= student.l_name %></td>
<td><%= student.date_submit %></td>
<td><%= student.floor_pref %></td>
<td><%= #selected_room %></td>
<% form_tag do %>
<% if student.floor_pref == '1st' %>
<td><%= select_tag 'room', options_for_select(#first_floor.map { |value| [value,value]}, #selected_room) %></td>
<% end %>
<% if student.floor_pref == '2nd' %>
<td><%= select_tag 'room', options_for_select(#second_floor.map { |value| [value,value]}, #selected_room) %></td>
<% end %>
<% if student.floor_pref == '3rd' %>
<td><%= select_tag 'room', options_for_select(#third_floor.map { |value| [value,value]}, #selected_room) %></td>
<% end %>
<td><%= submit_tag 'Update' %></td>
<% end %>
<td><%= button_to 'Show', :controller => 'students', :action => 'preview', :id => student%></td>
<td><%= button_to 'Remove', student, method: :delete, data: { confirm: 'Are you sure?' } %></td>
</tr>
<% end %>
button_tag creates a form on your page. The problem that you have right now is that the select_tag dropdown is not part of that form. What you probably want to do is to create the form explicitly and have the dropdown be inside of it. Replace your last 2 td's with something like this:
<%= form_tag do %>
<% if student.floor_pref == '1st' %>
<td><%= select_tag 'room', options_for_select(#first_floor.map { |value| [value,value]}, #selected_room) %></td>
<% end %>
<% if student.floor_pref == '2nd' %>
<td><%= select_tag 'room', options_for_select(#second_floor.map { |value| [value,value]}, #selected_room) %></td>
<% end %>
<% if student.floor_pref == '3rd' %>
<td><%= select_tag 'room', options_for_select(#third_floor.map { |value| [value,value]}, #selected_room) %></td>
<% end %>
<td><%= submit_tag 'Update' %></td>
<% end %>

Resources