ActiveRecord Finder & Query Methods
In my domain I have a company that has_many kpis with a goal value associated to it. Each company kpi has_many metrics or “metric updates”. The idea behind this is that a company is able to update each of the kpis’ progress towards their goal by adding new metric updates. However, I felt it was important to save all of these metrics so that the team could see progress charted over time. Thus, a “metric update” is really creating a new metric that belongs_to the company’s kpi. In coding this portion of my app I found a couple of Rails specific methods infinitely helpful in keeping my code clean.
I’ve come to despise code that uses uses conditional statements like this using nil because, well, it doesn’t sound like plain English and it’s ugly. I find SQL sort statements to be entirely unpleasant and have fallen for ActiveRecord’s auto-magic methods Exists? ActiveRecord Finder method and ActiveRecord Ordering Query Methods.
if something == nil return somethingelse end
SELECT "metrics".* FROM "metrics" WHERE "metrics"."kpi_id" = ? ORDER BY "metrics"."created_at" DESC
I mean just look how beautiful and effortless these methods make my particular example. <3
<%@company.kpis.each do |kpi|%> <%if kpi.metrics.exists?%> <ul class="collection"> <%kpi.metrics.order(created_at: :desc).each do |mt|%> <li class="collection-item"> Last Updated to <%=mt.metric%> on <%=mt.created_at.to_formatted_s(:long)%> <%=link_to "Delete", company_kpi_metric_path(@company, kpi, mt), method: :delete %> </li> <%end%> </ul> <%end%> <%end%>