• Category Archives: ActiveRecord::Relation

[ActiveRecord] Get a polymorphic owner class out of the owned object

The question is: how can we retrieve a owners class of a polymorphic association without loading the owner object into memory? Solution There are (at least) two ways to do this. First one is not recommended (as it might fail with multiple namespaces with same class names, etc: or a better one that will work […]

Read more at the source

Extending ActiveRecord association to cleanup your associations code

For some reason not many RoR developers know that they can extend ActiveRecord associations. This feature can be a great way to cleanup any relational code that is dependent on a parent resource (or to just add a simple functionalities to scopes). Here’s a really simple example how you can use it: That way you […]

Read more at the source

ActiveRecord count vs length vs size and what will happen if you use it the way you shouldn’t

One of the most common and most deadly errors you can make: using length instead of count. You can repeat this multiple times, but you will always find someone who’ll use it the way it shouldn’t be used. So, first just to make it clear: #count – collection.count Counts number of elements using SQL query […]

Read more at the source

ActiveResource relations – a bit of magic to make it look and feel more like ActiveModel relations

ActiveResource collection new problem ActiveResource can be pretty helpful when you have a RESTful JSON API. Although it has some limitations. One of the most irritating is a lack of nested resources new scope method. When you have structure like this: You can do some basic stuff: But unfortunately if you try something like this: […]

Read more at the source
close