Hopefully a simple question around a rails best-practice.
Let’s keep this super simple; say I have a task model that has an ID, description and status.
In my controller I have an index action to return all tasks
def index
@tasks = Task.all
end
My question is, in my view, suppose I want to display the tasks in separate HTML tables according to their status.
What is the best practice?
a) Query the database multiple times in the index action, ie
def index
@draft_tasks = Task.where(status: "Draft")
@approved_tasks = Task.where(status: "Approved")
@closed_tasks = Task.where(status: "Closed")
end
b) Query the database once, and filter in the contoller action
def index
tasks = Task.all
@draft_tasks = tasks.#somethinghere
@approved_tasks = tasks.#somethinghere
@closed_tasks = tasks.#somethinghere
end
c) Filter in the view
<% @tasks.each do |k, v| %>
<% some if statement searching for the status I want %>
# Some code to output the table
<%end%>
<%end%>
or
d) Something else?
The generally accepted best practices here are to keep controller methods thin and to keep logic out of the view. So with that in mind, one possible way to do this would be:
This will make 3 queries to the database, which could become a performance concern down the road, but if that does happen, you can optimize it at the model level (e.g. by defining class methods
drafts,approved, andclosedwhere the first one called prefetches everything). It’s less elegant though, so don’t prematurely optimize.