I have 2 models: task
and request_task
. They are different tables because they are very different items.
I also have a "My Tasks" portion of my application where I want to show a single list that combines both tasks
and request_tasks
ordered by due_date
.
I see a few options, but I'm not sure which is the cleanest approach. I'm trying to find a solution that is as simple as possible and follows most conventions.
(1) Two DB queries and join/order in Ruby
This would work, but is slow and not performant, in my opinion. I would rather use the power of a DB to select and order data instead of Ruby. This list could potentially be a few hundred records.
# Pseudocode
tasks = current_user.tasks
request_tasks = current_user.request_tasks
sorted_records = (tasks + request_task).sort! { |a, b| a.due_date <=> b.due_date }
(2) SQL Query to make one DB query
I would prefer something like this, but the issue is I don't know how to take the records and instantiate the proper model (task
or request_task
). I'm also not very good at the SQL required for this:
class AbstractTask
def records
# Some ActiveRecord/SQL that selects filtered Tasks and RequestTasks from DB and instantiates proper model
end
end
# Combines Tasks and RequestTasks that match criteria and are ordered
records = AbstractTask.records.where(user_id: current_user.id).order(:due_date)
(3) Use Single-Table Inheritance to reduce to a single table
This "works", but then I'll have a bunch of unused attributes because tasks
and request_tasks
are pretty different.
But this has the benefit of being able to query a single table and return a list of all relevant records.
This may be the simplest approach at the moment. I think it will give me everything I want, just with some unused attributes for half the records. That trade-off may be worth it if there's no other clean solution.