delegate with has_many not possible in Rails

Rails delegations give you convenient methods, but it turns out you can't delegate to has_many relations, due to the way Rails implements it. I'm not sure if it's a bug, but essentially, I had a structure like:

In city.rb, I wanted to rewrite the #sub_cities_names method as a delegate, but:

Looking at the source, this makes sense. Anything with "sub_city" just won't work because the relation is "sub_cities," and at that point it returns ActiveRecord::Relation, so I can't do much from there.

edit: this is a little closer, but kinda ugly:

1 comment:

  1. Actually, you can delegate any method, so long as it's a method that the resulting collection has a available to it. Rails returns an ActiveRecord::Relation, which acts a lot like an array, so you can delegate things like `each` and `collect` and `first`