ActiveRecord “select” results of model method

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

Mixes#index grabs @mixes = Mix.where(:active => true) and mixes/index.html.erb looks like this:

<% @mixes.each do |mix| %>
    <li><%= link_to mix.display_title, mix %></li>
<% end %>

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"display_title").where(:active => true) but it fails because display_title is not a real DB column


You can do"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 Arel commands, consider putting the select into a model method:

def select_active_titles
  select("sc_title, override_title").where(:active => true)

Edit: Your link_to helper also secretly calls to link to the right mix, so make sure it's working and if not add id to the list of selected attributes.

Need Your Help

Event to NumericUpDown for only user interaction

c# forms winforms events numericupdown

I have 3 NumericUpDown elements in my form. This elements is synchronized by their sum. For example sum is 9 elements values is 3,3,3 and increment is 2. When user is changed first element up from ...

Suggestions on how to add the functionality to import Finale music files on an application?

parsing music

I'm working on a music writing application and would like to add the functionality to import Finale music files. Right now, the only thing I know is that they are enigma binary files.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.