This project is archived and is in readonly mode.
Array of records from ActiveRecord Association does not behave as expected
-
Matt Jones
- State changed from new to wontfix
This behavior is by design - @record.contracts doesn't actually return an Array, but an instance of AssociationCollection that mostly pretends to be an array. This lets you do things like:
@record.contracts.exists?(@some_contract)which does a specific SQL query if
@record.contractsisn't loaded yet, avoiding that database overhead. It also permits you to chain named scopes onto an association (@record.contracts.some_scope) and build/create associated records (with@record.contracts.build, etc.).If you really want to remove all the magic,
@record.contracts.to_awill do what you're looking for. -
Kent T
I don't wish to remove any of the magic of @record.contracts.
However, when I instantiate an array from @record.contracts, should the array be an Array or an instance of AssociationCollection?Example
all_contracts = @record.contracts
all_contracts would be an array
@record.contracts would be an instance of AssociationCollection
Interestingly enough, when I printed the class of all_contracts it shows as an array, but it behaves like AssociationCollection. This is what I don't understand.
-
Matt Jones
This is a common gotcha in Ruby - objects are pretty much passed around as references. An example:
a = [1,2,3] b = a a << 4 b # => [1,2,3,4]So in your example, all_contracts is still an instance of AssociationCollection (although it fibs in the .class method and claims to be an Array). There are some ways to tell the two apart, though - all_contracts.respond_to?(:proxy_reflection) will return true, not that one typically needs to figure out that difference in standard Rails code.
Anyway, if you have further questions, feel free to ask on the rails-talk list to avoid cluttering up Lighthouse.
-
Rohit Arondekar
- Tag changed from activerecord associations, habtm to activerecord, associations, habtm