Merrick Johnson wrote:
this creates a method for the resource. in this case it returns the newest 3 records.
Yup!
> This is pretty helpful because i can call this from a
view or partial ( @story.votes.latest ) and just get the newest three votes. This should work in any DB ( im using Oracle11G )
And you never need to say that about MVC or ActiveRecord. The point is you write the minimum code, all in the right places, to support the maximum features. You don't have to do it the old-fashioned way, with code scattered everywhere, all very similar, getting in the way of each other!
Now this is why that new aggregation notation is so dang cool. Here's the Rails 1 way to do a bunch of links:
class Customer
has_many :accounts
has_many :accounts_cc, :class_name => 'Account',
:conditions => { :kind => 'cc' }
has_many :accounts_ach, :class_name => 'Account',
:conditions => { :kind => 'ach' }
end
Now compared to raw SQL, has_many is already an order of magnitude more DRY (Don't Repeat Yourself). Yet the one requirement to distinguish Credit Card from Checking accounts forces us to create three very wet has_many calls on the same model. They are, once again, irritatingly similar.
Here's the (apparent!) Rails 2 fix:
class Customer
has_many :accounts do
def kind(k)
find :all, :conditions => { :kind => k }
end
end
end
Boom done. You can write customer.accounts, customer.accounts.kind('cc'), and customer.accounts.kind('ach'), all very similar to what you could write before, but with far fewer executable lines.
I'm stoked because we just spent 3 days refactoring a big system which needed this exact fix, and I didn't know about it. Now I get to install it on Monday. Merry Xmas to me, huh?!