# Active record associations

**URL:** <https://www.ruby-forum.com/t/active-record-associations/152755>\
**Category:** Rails\
**Created:** [November 7, 2008, 5:18am UTC](https://www.ruby-forum.com/t/active-record-associations/152755 "2008-11-07T05:18:37Z")\
**Posts on this page:** 1\
**Page:** 1

<div class="post-metadata">

**Author:** ![obenhauser](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/o/d78d45/32.png) [@obenhauser](https://www.ruby-forum.com/u/obenhauser)\
**Post date:** [November 7, 2008, 5:18am UTC](https://www.ruby-forum.com/t/active-record-associations/152755/1 "2008-11-07T05:18:37Z")

</div>

What’s wrong with ruby associations?

Somehow association fields don’t have any support for dirty objects  
nor optimistic locking.

I would expect dirty objects to work like this:

class Person  
has\_many :cars  
end

> > person = Person.find\_by\_name(“Jack”)  
> > person.cars

=\> [#\<Car id: 2, name: “BMW”, created\_at: “2008-11-04 03:04:46”,  
updated\_at: “2008-11-04 03:04:46”\>]

> > person.cars=[Car.find\_by\_name(“Porsche”), Car.find\_by\_name(“VW”)]  
> > person.cars

=\> [#\<Car id: 1, name: “Porsche”, created\_at: “2008-11-04 03:04:46”,  
updated\_at: “2008-11-04 03:04:46”\>, #\<Car id: 3, name: “VW”,  
created\_at: “2008-11-04 03:04:46”, updated\_at: “2008-11-04 03:04:46”\>]

> > person.changed?  
> > =\> true
> 
> > person.changes

=\> {“cars”=\>[[#\<Car id: 2, name: “BMW”, created\_at: “2008-11-04  
03:04:46”, updated\_at: “2008-11-04 03:04:46”\>], [#\<Car id: 1, name:  
“Porsche”, created\_at: “2008-11-04 03:04:46”, updated\_at: “2008-11-04  
03:04:46”\>, #\<Car id: 3, name: “VW”, created\_at: “2008-11-04  
03:04:46”, updated\_at: “2008-11-04 03:04:46”\>]]}

> > person.save #associations are saved in the database

However ror returns the following

> > person = Person.find\_by\_name(“Jack”)  
> > person.cars

=\> [#\<Car id: 2, name: “BMW”, created\_at: “2008-11-04 03:04:46”,  
updated\_at: “2008-11-04 03:04:46”\>]

> > person.cars=[Car.find\_by\_name(“Porsche”), Car.find\_by\_name(“VW”)] #associations are saved in the database  
> > person.cars

=\> [#\<Car id: 1, name: “Porsche”, created\_at: “2008-11-04 03:04:46”,  
updated\_at: “2008-11-04 03:04:46”\>, #\<Car id: 3, name: “VW”,  
created\_at: “2008-11-04 03:04:46”, updated\_at: “2008-11-04 03:04:46”\>]

> > person.changed?  
> > =\> false
> 
> > person.changes

=\> {}

The same problem happens with optimistic locking

p1 = Person.find\_by\_name(“Jack”)  
p2 = Person.find\_by\_name(“Jack”)

p1.cars = [Car.find\_by\_name(“Porsche”)]  
p1.save

p2.cars = [Car.find\_by\_name(“BMW”)]  
p2.save

I would expect the object to raise an exception, but it doesn’t.

Isn’t there a way to unify the behaviour of regular fields and  
associations? Most objects in my app don’t represent flat tables, but  
tables that associate each other. Right now I’m forced to having to  
wrap many attribute updates into a transaction and write my own object  
comparisons.
