I’m a Rails beginner and to learn it I’m building a simple time tracking app. I want to populate an administrator’s dashboard with a ton of information from many tables with nested information.
What would be the best practice for querying the database to request all of the data for one company to view a dashboard of all clients, projects, tasks, adjustments and minutes?
Here’s how the data is structured:
Company
has_many clients
Client
belongs_to company
has_many projects
Project
belongs_to client
has_many tasks
Task
belongs_to project
has_many minutes
Minute
belongs_to task
This data structure might be really bad. I don’t know.
An example view of the data:
Activision
— Website Redesign
— Development
—- 100 Minutes
I’m starting with this but I’m pretty but it could be totally backwards (Users belong to Companies):
@clients = Client.find_all_by_company_id(current_user.company_id)
@clients.each do |client|
project = Project.find_all_by_client_id(client.id)
puts project.name
project.each do |project|
task = Task.find_all_by_project_id(project.id)
puts task.name
end
end
I guess the question can also be asked: Is there a good book or resource that fully describes Rails ActiveRecord best practices?
Use the
includesmethod to eagerly load the associations.Example from the guides
Based on what you said, that should be:
This is a horrible Law of Demeter violation, if any of these things change at any point, whether in their structure or naming, we will have to come fix this code. I’m not really sure how to deal with that without introducing lots of abstractions.
Regarding a book, there have been many, but I honestly don’t think the Rails world has figured out yet what constitute best ActiveRecord practices (in fact, there’s a large portion of the community that thinks almost all ActiveRecord practices are just terrible — I’m mostly in that camp).
But if you want things like the above, which says to use
#includesto eager load associations, then the guides are a great place to find out information like that. I also really enjoyed this blog and videos.