I have a problem with my Ruby application. I created users who are associated with a resource (resource_id). The working hours of the users indicate the capacity of the resource. The resource table should display the total capacity of the resources. The total capacity of the resource results from the sum of the capacities of the users assigned to the respective resource. However, in the resource table, the same capacity is displayed for each resource (the sum of all resources).
As an an example:
I have 2 use, which each work 8 hours:
User 1: capacity 8, resource_id 1
User 1: capacity 8, resource_id 2
Now there should be 2 resources in the resource table, each with a capacity of 8. With me however both resources with a capacity of 16 ..
Here are the corresponding index files, controllers and models.
resources.index
<% provide(:title, 'Ressourcen') %>
<p id="notice"><%= notice %></p>
<h1>Ressourcen</h1>
<table id="resources" class="display">
<thead>
<tr>
<th>Name</th>
<th>Gesamtkapazität</th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<% #resources.each do |resource| %>
<tr>
<td><%= resource.name %></td>
<td><%= User.sum(:capacity, :conditions => {:resource_id => resource}) %></td>
<td><%= link_to 'Anzeigen', resource %></td>
<td><%= link_to 'Entfernen', resource, method: :delete, data: { confirm: 'Sind Sie sich sicher?' } %></td>
<% end %>
</tr>
</tbody>
</table>
resource.model:
class Resource < ActiveRecord::Base
def resource_params
params.require(:resource).permit(:created_at, :name, :ocr, :cost, :oce)
end
validates :name, presence: true, uniqueness: true, length: {maximum: 50}
has_many :procedure_resources, :dependent => :destroy
has_many :procedures, through: :procedure_resources
has_many :users, :dependent => :destroy
end
resource.controller:
class ResourcesController < ApplicationController
before_action :set_resource, only: [:show, :edit, :update, :destroy]
# GET /resources
# GET /resources.json
def index
#resources = Resource.all
#procedures = Procedure.all
#project = Project.find(1)
end
def show
#resource = Resource.find(params[:id])
end
private
def set_resource
#resource = Resource.find(params[:id])
end
def resource_params
params.require(:resource).permit(:name, :oce, :oce, :cost, :ocr)
end
end
users.model:
class User < ActiveRecord::Base
belongs_to :resource
Does anyone know how I managed it, that it only shows the capacity of the respective resource in the resource.index?
The error must be in the resource.index with the following line:
<td> <% = User.sum (: capacity,: conditions => {: resource_id => resource})%> </ td>
or?
Best regards,
Phillip
Related
for some reason this page wont opening using ruby on rails 5. Its giving me a undefined method `name' for nil:NilClass error.
The code was working perfectly the last time i opened it. can anyone please help? It would be very much appreciated.
here the the view page.
<h1> Your sale history page </h1>
<table class="table table-bordered table-hover table-striped">
<tr>
<th>Image</th>
<th>Title</th>
<th>Label</th>
<th>Condition</th>
<th>Customer</th>
<th>Price</th>
<th>Date Sold</th>
</tr>
<% #orders.each do |order| %>
<tr>
<td><%= image_tag order.record.image.url(:thumb)%></td>
<td><%= order.record.Title %></td>
<td><%= order.record.Label %></td>
<td><%= order.record.Condition %></td>
<td><%= order.buyer.name %></td>
<td><%= order.record.Selling_Price %> </td>
<%#THE BELOW CODE IS FOR RUBY DATE. FOUND ON rubydoc%>
<td><%= order.created_at.strftime("%-d %B, %Y") %></td>
<td>
</tr>
<%end%>
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
#the below code validates that the name present
validates :name, presence: true
#the below code tells rails that a user has many records. and that if a user is deleted so is the record
has_many :records, dependent: :destroy
has_many :sales, class_name:"Order", foreign_key: "buyer_id"
has_many :reviews, dependent: :destroy
end
class Order < ApplicationRecord
#the below validates the form fields
validates :address,:town_or_city,:state_or_county,:post_or_zip_code,:country, presence: true
belongs_to :record
# the below code tells rails that the relationship is two sided. a user can be a buyer or a seller
belongs_to :buyer, class_name:"User"
belongs_to :seller, class_name:"User"
end
Ok I guess you need quick fix put
<td><%= order.try(&:buyer).try(&:name) %></td>
this will make sure you do not get error if ther is no buyer than see witch order is without buyer
Does order table have buyer_id on all records?
Maybe, there are records where buyer_id is null.
Or order can't get buyer because there isn't matching id.
I found below link useful to know more about 'try' usage and why 'try' is better over rescue nil option in the above scenario.
https://rubyinrails.com/2015/08/27/rescue-nil-in-ruby-on-rails
I am new to ruby on rails and am working on a project.I am working on the HTML part.Actually i want to display the name for a particular Id.But am getting a Fixnum error saying
Undefined method 'name' for 1:Fixnum
What does this signify.
The two tables i am trying to connect are loan fines and books.I am using the id of the book to get the name of the book.
The Html I am using is :-
<h1 class="List">Listing Loan Fines</h1>
<table class="table table-bordered" >
<tr>
<th>ID</th>
<th>Category Id</th>
<th>Loan Duration in Days</th>
<th>Book Name</th>
<th>Fine Amount</th>
<th>Fine Duration</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<% #loan_fines.each do |c| %>
<tr>
<td><%= link_to c.id, {:action => 'show', :id => c.id} %> </td>
<td><%= c.category_id %> </td>
<td><%= c.loan_duration %> </td>
<td><%= c.book_id.name %> </td> <----Trying to get book name here
<td><%= c.fine_amount %> </td>
<td><%= c.fine_duration %> </td>
<td><%= link_to 'Edit', {:action => 'edit', :id => c.id} %> </td>
<td><%= link_to 'Delete', {:action => 'delete', :id => c.id},
:data => { :confirm => "Are you sure you want to delete this value?" } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Loan fine', new_loan_fine_path %
My book model is as follows :-
class Book < ActiveRecord::Base
# Virtual attribute
attr_accessor :author_full_name
attr_accessible :title, :abstract, :isbn, :reference_no, :category_id, :author_last_name, :author_first_name
attr_accessible :publisher, :call_no, :book_location, :library_location_id, :author_middle_name
attr_accessible :edition, :deleted, :total_num_copies, :cost, :entered_by, :last_updated_by, :image, :author_full_name
# -------- Carrierwave ------------
mount_uploader :image, ImageUploader
# ------- ASSOCIATIONS --------
has_many :book_holds
has_many :book_transactions
has_many :loan_fines
belongs_to :admin, :foreign_key => 'last_updated_by'
belongs_to :admin, :foreign_key => 'entered_by'
belongs_to :library_location
belongs_to :category
# -------- SCOPES ----------
default_scope :order => 'books.id DESC'
scope :not_deleted, where("books.deleted = 0")
default_scope not_deleted
# ------ VALIDATIONS ------
validates :isbn, :allow_blank => true, :uniqueness => { :case_sensitive => false }
validates :reference_no, :allow_blank => true, :uniqueness => { :case_sensitive => false }
validates :call_no, :allow_blank => true, :uniqueness => { :case_sensitive => false }
#----------------------------------------------------------------------------
# author_full_name - Returns Full Name of author
#----------------------------------------------------------------------------
def author_full_name
"#{author_last_name}, #{author_first_name} #{author_middle_name}"
end
end
My loan fines model is as follows:-
class LoanFine < ActiveRecord::Base
attr_accessible :book_id, :category_id, :loan_duration, :fine_amount, :fine_duration
# ------- ASSOCIATIONS -----------
belongs_to :book
belongs_to :category
# ------ VALIDATIONS ------
# validate :book_or_category
# if [self.book_id, self.category_id].reject(&:blank?).size == 0
# if self.book_id.blank? && self.category_id.blank?
#end
end
Can someone please help me with this as I am new in this
Of course you cannot call method name for a number. Try to use c.book.name.
You just need to do following
<%= c.book.name %>
Change <%= c.book_id.name %> to <%= c.book.name %>
I am attempting to learn how to increase the performance of Rails applications and the first step I am looking at is eager loading.
I've configured the bullet gem which shows where I can make use of eager loading, however, I'm not too sure how to make use of the help!
An example log is:
2012-04-26 15:59:34
0.0.0.0:3000http://0.0.0.0:3000/animals
N+1 Query detected
Animal => [:client]
Add to your finder: :include => [:client]
N+1 Query method call stack
N+1 Query method call stack
/Users/dannymcclelland/Projects/premvet/app/views/animals/index.html.erb:26:in `block in _app_views_animals_index_html_erb__2796162405947806753_70316525286320'
/Users/dannymcclelland/Projects/premvet/app/views/animals/index.html.erb:22:in `_app_views_animals_index_html_erb__2796162405947806753_70316525286320'
/Users/dannymcclelland/Projects/premvet/app/controllers/animals_controller.rb:7:in `index'2012-04-26 15:59:34[WARN] user: dannymcclelland
0.0.0.0:3000http://0.0.0.0:3000/animals
Unused Eager Loading detected
Animal => [:id, :AnimalName, :Species]
Remove from your finder: :include => [:id, :AnimalName, :Species]2012-04-26 16:00:56
The lines that jump out are:
N+1 Query detected
Animal => [:client]
Add to your finder: :include => [:client]
and
Unused Eager Loading detected
Animal => [:id, :AnimalName, :Species]
Remove from your finder: :include => [:id, :AnimalName, :Species]
What I am unsure of, is what is the definition of the 'finder'. Is it the block in the view or is it in the controller.
Taking the first section of log that jumps out at me the controller is as follows:
def index
#animals = Animal.page(params[:page]).per_page(15)
respond_to do |format|
format.html # index.html.erb
format.json { render json: #animals }
end
end
the model:
class Animal < ActiveRecord::Base
self.table_name = 'animal'
self.primary_key = 'PVID'
attr_accessible :AddedBy, :Age, :AnimalBFAmount, :AnimalBalance, :AnimalName, :Archive, :BillType, :Breed, :ChronicStatus, :Class, :Classification, :ClientKey, :Colour, :Date1, :DateOfBirth, :DateofBirth, :Dead, :DiaryQueue, :DiscField, :DrugsAtCost, :DrugsNoVAT, :ESDAmount, :ESDType, :FNote, :FirstRegisteredDate, :Height, :IDNumber, :Insured, :InsuredWith, :IsClient, :IsClientDate, :IsMaster, :LastBilledAmount, :LastBilledDate, :LastConsDate, :LastContributionDate, :LastPaidDate, :LastWeightDate, :Locked, :LoyaltyMultiplier, :LoyaltyPoints, :MR_Flag_0, :MR_Flag_1, :MR_Flag_10, :MR_Flag_11, :MR_Flag_12, :MR_Flag_13, :MR_Flag_14, :MR_Flag_15, :MR_Flag_2, :MR_Flag_3, :MR_Flag_4, :MR_Flag_5, :MR_Flag_6, :MR_Flag_7, :MR_Flag_7, :MR_Flag_8, :MR_Flag_9, :Mileage, :Neutered, :NextApptDate, :ORT, :OldSex, :Opt_Flag_0, :Opt_Flag_1, :Opt_Flag_2, :Opt_Flag_3, :Opt_Flag_4, :Opt_Flag_5, :Opt_Flag_6, :Opt_Flag_7, :PVID, :PreferredContact, :PreferredUser, :Ref1, :RefPrac, :ReferredBy, :SSDType, :SeenInPeriod, :SendBill, :Sex, :SiteAnimal, :Species, :Status, :SurcAmount, :SurcType, :SurgeryNumber, :TBU, :TOSAmount, :TOSDrugs, :TOSFees, :TOSType, :Weight
belongs_to :client, :foreign_key => 'ClientKey'
has_many :clinicals, :foreign_key => 'PVID'
has_many :labs, :foreign_key => 'PVID'
has_many :consults, :foreign_key => 'pvid'
has_many :sheets, :foreign_key => 'PVID'
default_scope :order => "Dead ASC, AnimalName ASC"
end
Note that I'm using a legacy database hence the strange column names etc.
The view contains the following:
<% #animals.includes(:client).each do |animal| %>
<tr>
<td><%= animal.id %></td>
<td><%= animal.AnimalName %></td>
<td><%= link_to animal.client.Surname, animal.client %></td>
<td><%= animal.Species %></td>
<td><%= animal.Breed %></td>
<td><%= animal.Dead %></td>
<td><%= link_to 'Show', animal %></td>
</tr>
<% end %>
So, should I be adding the other recommended columns to the view 'finder'? Or somewhere else?
Any help would be appreciated!
In your controller, you want to update your query to include the client:
#animals = Animal.includes(:client).page(params[:page]).per_page(15)
I have following structure:
class User < ActiveRecord::Base
has_many :Hobbies, :dependent => :destroy
accepts_nested_attributes_for :hobbies, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
class Hobby < ActiveRecord::Base
belongs_to :User
end
In my Users_controller.rb
def index
#data = User.all(:joins => :hobbies)
end
In index.html.erb
<% for item in #data %>
<tr>
<td><%= item.id %></td> #from table Users
<td><%= item.hobby_name %></td> #from table Hobbies
</tr>
<% end %>
And this gives me an error undefined method `hobby_name' for # User:0x103cf7480>
I thought that I have that associations right, but this error makes confused... Can you help me someone, please, where could be a problem?
You must specify the relation, your object doesn't have an attribute called hobby_name, it has an association to multiple hobbies, and each hobby has an attribute called hobby_name
So:
<% item.hobbies.each do |h| %>
<%= h.hobby_name %>
<% end %>
I have 2 models, car and registrations.
class Car < ActiveRecord::Base
belongs_to :Registration
end
class Registration < ActiveRecord::Base
has_many :cars, :dependent => :destroy
accepts_nested_attributes_for :cars, :reject_if => lambda { |a| a[:content].blank? }, :allow_destroy => true
end
In CarsController:
def index
#cars = Car.all
#cars2 = Car.all(:joins => :Registration)
end
In view:
<% #cars.each do |car| %>
<tr>
<td><%= car.twitter %></td>
<td><%= car.facebook %></td>
<td>
<% #cars2.Registration.each do |h| %> #here is my problem
<%= h.email %>
<% end %>
</td>
</tr>
<% end %>
This is my statement of cars. I am trying to print for every car owner's email. The email is in table Registration (model registration). I don't know how to make a query to database, that I want to get email from table Registrations, when column registration_id in table Cars == id column of table Registrations...
So I would like to ask you, if you have a tip, how to do...
You have got your associations in capital letters. It should be in small like this
class Car < ActiveRecord::Base
belongs_to :registration
end
Also you dont have to assign 2 variables in the controller
def index
#cars = Car.includes(:registration)
end
and in the view
<% #cars.each do |car| %>
<tr>
<td><%= car.twitter %></td>
<td><%= car.facebook %></td>
<td>
<%= car.registration.email %> #here is my problem
</td>
</tr>
<% end %>
Use this instead to fetch the email:
<%= car.registration.email %>
If you want eager loading, then use the following line in your controller instead:
#cars = Car.includes(:registration)
There's no need for #cars2.