My name is MatthewRudy, and I'm a Rails Developer. I am.... MATTHEW RUDY ON RAILS!!!


Select which columns to "reload" with ActiveRecord

There was an interesting ticket on the Rails Lighthouse today.

Regarding;

How can I just reload a couple of columns for a given record?

The suggested solution was a new method for each attribute


record.reload_name

or

record.reload(:name)

or

record.name!



however,
we can already do this.



record.reload(:select => "name")

or

record.reload(:select => "name, other_column")

or even

record.reload(:select => "COUNT(SELECT * FROM other_table WHERE foreign_key = this_table.id) AS other_count")
record.other_count == "12"



This is all down to the nice way that .reload(options) works.

Basically coming down to this;



def reload(options=nil)
new_model = self.class.find(self.id, options)
self.attributes.update(new_model.attributes)
return self
end


(see the real code over at github

So it only actually updates the attributes we end up reloading.
nice!