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.
Related
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
Good Day
i have model
Food
Dayoffer
Food which is records with all foods in our canteen
class Food < ApplicationRecord
belongs_to :supplier
has_many :dayoffer
end
Dailyoffer is restricted set of foods which are offered on some day.
class Dayoffer < ApplicationRecord
belongs_to :food
end
i dont know how to effectively save choices for day
i have idea to use in form collection_check_boxes but dont know how to process it effectively.
schema of db on
https://gist.github.com/netmoleCBA/089950c54a4b8e066da8afc54fa5a62e
Add a WeekDay model that has many offers and seed seven week days in your database :
in your food form:
<%= f.collection_check_boxes(:week_day_ids, WeekDay.all, :id, :name) do |week_day| %>
<%= week_day.label { week_day.check_box } %>
<% end %>
D'ont forget to add week_day_ids in the controller's strong params
params.require(:food).permit(:name, week_day_ids:[])
Been going through http://guides.rubyonrails.org/association_basics.html but can't seem to get my head around this
I have 4 models: users, listings, comments, commentresponses. Somebody creates a listing, someone else can comment on the listing, then the original creator can respond to the comment.
class User < ActiveRecord::Base
has_many :comments, foreign_key: 'provider'
has_many :listings
has_many :comments
has_many :commentresponses
end
class Listing < ActiveRecord::Base
belongs_to :user
end
class Comment < ActiveRecord::Base
belongs_to :listing
belongs_to :user
has_one :commentresponse
end
class Commentresponse < ActiveRecord::Base
belongs_to :comment
belongs_to :user
end
Everything is working well except I can't access comment.commentresponse; this give a no method error.
Any recommendations of where my logic is wrong?
Associations
I wouldn't use a separate model for CommentResponse; keep it all in the Comment model - using a gem such as ancestry to give a parent / child system to the different comments:
Above is an example of one our Category models - showing how you can order the different associations with the likes of the ancestry gem. The reason why I posted is because this is how you can create responses to your comments, rather than having a separate model:
#app/models/user.rb
class User < ActiveRecord::Base
has_many :listings
has_many :comments
end
#app/models/listing.rb
class Listing < ActiveRecord::Base
belongs_to :user
end
#app/models/comment.rb
class Comment < ActiveRecord::Base
belongs_to :listing
belongs_to :user
has_ancestry #-> make sure you have "ancestry" column with string in db
end
This basically allows you to use the various methods which ancestry appends to your objects:
Ancestry
I would recommend using the Ancestry gem to store the responses of the comments. You can then add to this by using several partials to provide a nested interface. This way, it will show you the comments you want, with the correct responses etc
IMPORTANT
When using ancestry - you define the parents of the rows with comment_1/comment_2. Many people think you have to just define the "parent"; not true. You have to define the entire "history" of the ancestors of an object
--
Tree
If you go with the ancestry approach, you'll be able to do something like the following:
To achieve this, you can use the nested partial we created here (obviously replace for use with comments):
#app/views/categories/index.html.erb
<%= render partial: "category", locals: { collection: #categories } %>
#app/views/categories/_category.html.erb
<ol class="categories">
<% collection.arrange.each do |category, sub_item| %>
<li>
<!-- Category -->
<div class="category">
<%= link_to category.title, edit_admin_category_path(category) %>
</div>
<!-- Children -->
<% if category.has_children? %>
<%= render partial: "category", locals: { collection: category.children } %>
<% end %>
</li>
<% end %>
</ol>
I know it's not a direct answer to your question; it certainly should help you though
I'm building a guestlist app and I have defined both Guest (name) and List models - guests can have many lists and lists can have many guests. Both are associated in a has_many through association (after reading that HABTM associations aren't a good idea).
Here are my models:
class Guest < ActiveRecord::Base
has_many :lists, through: :checklists
end
class List < ActiveRecord::Base
has_many :guests, through: :checklists
end
class Checklist < ActiveRecord::Base
belongs_to :list
belongs_to :guest
end
EDIT - my lists controller for show:
def show
#list = List.find(params[:id])
end
On the List show view, I want to display the all of the guest names that are tied to that list through the checklist table. I can figure out if I need a do loop or an array...this is a bit beyond my current skill.
I've tried things like the following:
<%= #list.checklist.guest.name %>
I'm clearly missing some key bit of code and concept here.
Thanks in advance.
You need to iterate over guests like this:
<% #list.guests.each do |guest| %> # For each guest in list.guests
<%= guest.name %> # print guest.name
<% end %>
It should be something like this
<% #list.guests.each do |guest| %>
<%= guest.name %>
<% end %>
I have three models User, Game and Point where a user gets points for playing games. What I'm trying to do is display the users with the most points for the most popular games in a view.
I used this question to determine the most popular games. So I now have this scope in Game.rb:
scope :most_popular_games,
select("games.id, name, count(points.id) AS points_count").
joins(:points).
group("games.id").
order("points_count DESC").
limit(5)
In my controller, I have this:
#most_popular_games = Game.most_popular_games
My models:
Models
class Point < ActiveRecord::Base
belongs_to :game
belongs_to :user
end
class Game< ActiveRecord::Base
has_many :points
end
class User < ActiveRecord::Base
# no relationship for points or games
end
class GameRank < ActiveRecord::Base
belongs_to :game
belongs_to :user
end
However, what I can't figure out what to do is create a way to now total the points per user for each of these games and make it so I identify each game differently, so I segment them out on the view (ie show the results separately for each game).
I tried adding this in the code, but I wasn't sure of the best way to make each game's results be identifiable in the view:
#most_popular_games.each do |most_popular_game|
most_points_for_popular_game = GameRank.where("game_id =?", most_popular_game.id).order('total_points desc').limit(10)
end
My question is basically how do I reuse the results for "most_points_for_popular_game" - which is the users with the most points for a given game - for each of the five games (#most_popular_games = five results)?
Totally ignoring N+1 queries and additional markup:
Add the :game_ranks relationship to Game:
class Game
has_many :game_ranks
end
Add a scope to GameRank:
class GameRank
scope :top, order('total_points desc').limit(10)
end
(I'm assuming a total_points column on GameRank based on your example)
In your view:
<% #most_popular_games.each do |game| %>
<%= game.name %>
<% game.game_ranks.top.each do |rank| %>
<%= rank.user.name %>,<%= rank.total_points %>
<% end %>
<% end %>