I have an employee NonAvailability model and instead of displaying all the non availabilities in the table with
<% #non_availabilities = NonAvailability.all %>
<% #non_availabilities.each do |non_availability| %>
<%= non_availability.employee.full_name %>
<%= non_availability.date %>
<%= non_availability.time %>
<%= non_availability.reason %>
I want to only display the nonavailabilities that correlate to a certain employees id.
How can I do this?
There are multiple ways to retrieve records in rails. For example you can filter NonAvailability with employee_ids using where method
ids = [1,2,3,4] # ids of employee
NonAvailabilty.where(employee_id: ids)
If you want to utilize method chaining, define a has_many and belongs_to association in your Employee and NonAvailability model. Assuming that your design have this specifications.
# employee.rb
class Employee
has_many :non_availabilities
end
# non_availability.rb
class NonAvailability
belongs_to :employee
end
Then you can retrieve all non_availabilites using employee object.
employee = Employee.find_by(id: 1)
employee.non_availabilities
For more info visit this Active Record Association Guide
Related
class Teacher < ActiveRecord::Base
has_many :students
end
class Class <ActiveRecord::Base
has_many :students
end
class Student <ActiveRecord::Base
belongs_to :teacher
belongs_to :class
end
I want to create a list of teachers, and below their names: table with classes from which this teacher has students and number of this students. More or less something like this:
Teacher XYZ:
Class 1A | 3 students
Class 3D | 2 students
How can I check if teacher has students from each class and later count only the students that belongs to both this particular teacher and class?
You can do a query to eager load the classes and students:
#teachers = Teacher.includes(students: :class)
Then I would use group_by in the view to group the students by the class.
<% #teachers.each do |teacher| %>
<%= teacher.name %>
<% teacher.students.group_by(&:class).each do |class, students| %>
<%= class.name %> | <%= students.size %>
<% end %>
<% end %>
I've assumed that a teacher and a class both have a name. There may well be a better way using something like has_many through but I can't see it at the moment.
On another note you shouldn't name your object Class it's going to cause you a lot of problems I'd have thought because it's defined in ruby already http://ruby-doc.org//core-2.2.0/Class.html. I'd call it something like SchoolClass to avoid conflicts.
I want to display has_many relationship columns in ransackable attributes list. So that I can display them in the dropdown.
I have a member model
class Member < ActiveRecord::Base
has_many :memberships
def self.ransackable_attributes(auth_object = nil)
if auth_object == 'admin'
super
else
super & ['first_name', 'last_name', 'license_number', 'memberships_membership_number_cont']
end
end
And membership model has some columns like membership_number which is unique and a string. Now in the dropdown of members listing page I want to provide membership_number, so that user can select membership_number from the dropdown and enter a value to search the respective member.
Any suggestions?
The dropdown I am taking about is:
PS: In the screenshot you may be looking for a dropdown for contains all/contain any ie options dropdown. I made is just one only contains any. Thats why its not visible.
You need to define the ransackable_attributes method in associated model for custom searchable attributes of that model. So your Membership model should be something like:
class Membership < ActiveRecord::Base
belongs_to :member
...
def self.ransackable_attributes(auth_object = nil)
['membership_number', ...]
end
end
And specify associations in ranssack form like:
<%= f.condition_fields do |c| %>
<%= c.attribute_fields do |a| %>
<%= a.attribute_select associations: [:memberships] %>
<% end %>
<% end %>
In my index I'm trying to iterate through records through records in 2 models, job and employer. I've set up a has_many relationship.
Rails its throwing a undefined method `each' for #
job model
attr_accessible :title, :location
belongs_to :employer
employer model
attr_accessible :companyname
has_many :jobs
job controller
def index
#jobs = Job.find(:all, :include => :employer)
index
<% #jobs.each do |job| %>
<%= job.title %>
<%= job.location %>
<% job.employer.each do |employer| %>
<% employer.companyname %>
<% end %>
<% end %>
That's because a job has one employer, not many. That's what the belongs_to means. See this Rails guide about setting up actual many-to-many relationships.
But I think in your case you do want it to be a one-to-many. Why would a job have multiple employers? Instead, just output the single employer company name.
More Info
You still want a belongs_to on your Job model. belongs_to go on models that have a foreign key referencing some other model. In this case, your Job model has an ID pointing at an Employer (it has an employer_id field). That has_one or has_many associations are for when no foreign key exists on the model but a relationship still exists.
So your Job model has a method called employer (singular) but not employers (plural) because it belongs to a single employer. An employer has many jobs under them, so the has_many association gives you a jobs (plural) method, not a job (singular) method.
The link I posted for the Rails guide does an excellent job of showing more of this, with more details and explanation, and more examples.
Addtional Code Bit
With the above, you will want to change your code to be like this:
<% #jobs.each do |job| %>
<%= job.title %>
<%= job.location %>
<%= job.employer.companyname %>
<% end %>
Notice how you can go straight to accessing the attributes on the employer that you want. And that will do it!
Have you tried running this in the rails console?
Job.last.employer
If that doesn't work your relationship isn't set up properly.
Does your Job model have an employer_id field? Did you run rake db:migrate to make sure all your migrations are run?
I have a model called Kase each "Case" is assigned to a contact person via the following code:
class Kase < ActiveRecord::Base
validates_presence_of :jobno
has_many :notes, :order => "created_at DESC"
belongs_to :company # foreign key: company_id
belongs_to :person # foreign key in join table
belongs_to :surveyor,
:class_name => "Company",
:foreign_key => "appointedsurveyor_id"
belongs_to :surveyorperson,
:class_name => "Person",
:foreign_key => "surveyorperson_id"
I was wondering if it is possible to list on the contacts page all of the kases that that person is associated with.
I assume I need to use the find command within the Person model? Maybe something like the following?
def index
#kases = Person.Kase.find(:person_id)
or am I completely misunderstanding everything again?
Thanks,
Danny
EDIT:
If I use:
#kases= #person.kases
I can successfully do the following:
<% if #person.kases.empty? %>
No Cases Found
<% end %>
<% if #person.kases %>
This person has a case assigned to them
<% end %>
but how do I output the "jobref" field from the kase table for each record found?
Maybe following will work:
#person.kase.conditions({:person_id => some_id})
where some_id is an integer value.
Edit
you have association so you can use directly as follows:
#kases= #person.kases
in your show.rhtml you can use instance variable directly in your .rhtml
also #kases is an array so you have to iterate over it.
<% if #kases.blank? %>
No Kase found.
<% else %>
<% for kase in #kases %>
<%=h kase.jobref %>
<% end %>
<% end %>
If your person model has the association has_many :kases then, you can get all the cases that belongs to a person using this
#kases = Person.find(person_id).kases
Assuming person_id has the id of the person that you want to see the cases for.
You would probably want something like
has_many :kases
in your Person model, which lets you do #kases = Person.find(person_id).kases
as well as everything else that has_many enables.
An alternate method would be to go through Kase directly:
#kases = Kase.find_all_by_person_id(person_id)
I have a company model and a person model with the following relationships:
class Company < ActiveRecord::Base
has_many :kases
has_many :people
def to_s; companyname; end
end
class Person < ActiveRecord::Base
has_many :kases # foreign key in join table
belongs_to :company
end
In the create action for the person, I have a select box with a list of the companies, which assigns a company_id to that person's record:
<%= f.select :company_id, Company.all.collect {|m| [m.companyname, m.id]} %>
In the show view for the person I can list the company name as follows:
<%=h #person.company.companyname %>
What I am trying to work out, is how do I make that a link to the company record?
I have tried:
<%= link_to #person.company.companyname %>
but that just outputs the company name inside a href tag but links to the current page.
Thanks,
Danny
You need pass in second argument the path where you want go
<%= link_to #person.company.companyname, #person.company %>
or with the full version :
<%= link_to #person.company.companyname, company_url(#person.company) %>
The thing is, link_to cannot guess where you want it to lead to, if you give it only the text of the link :)
In order to have the link lead to the company page, you need to add a path:
<%= link_to #person.company.companyname, company_path(#person.company) %>
This assumes you have proper restful routes for your company
map.resources :companies
and the page you're heading to is companies/show.html.erb.