I have a Rails app that pulls in music from Soundcloud. This data contains a title, which I save as mix.sc_title but it’s not always properly formatted. I have added an additional attribute on my Mix model which I call mix.override_title
For display on my site, I want to use the override title if available, and the sc_title in all other cases.
I have a Mix model method to do this for me
def display_title
override_title.blank? sc_title : override_title
end
Mixes#index grabs @mixes = Mix.where(:active => true) and mixes/index.html.erb looks like this:
<ul>
<% @mixes.each do |mix| %>
<li><%= link_to mix.display_title, mix %></li>
<% end %>
</ul>
As you can see, I’m not directly using any mix attributes, and so I take a huge hit when I go to the DB, and I don’t actually benefit from it.
Is there a leaner way to get just the information I need? (mix.display_title)
I have tried Mix.select("display_title").where(:active => true) but it fails because display_title is not a real DB column
You can do
Mix.select("sc_title, override_title").where(:active => true)and it will work, since those are the actual fields that the method uses. I don’t really think getting the additional attributes gives you that much of a DB hit but sometimes selecting only what you need can be beneficial.As you start chaining on more
Arelcommands, consider putting the select into a model method:Edit: Your
link_tohelper also secretly callsmix.idto link to the right mix, so make sure it’s working and if not add id to the list of selected attributes.