# Setting association values via id or objects

**URL:** <https://www.ruby-forum.com/t/setting-association-values-via-id-or-objects/127356>\
**Category:** Rails\
**Created:** [January 28, 2008, 4:03pm UTC](https://www.ruby-forum.com/t/setting-association-values-via-id-or-objects/127356 "2008-01-28T16:03:14Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [January 28, 2008, 4:03pm UTC](https://www.ruby-forum.com/t/setting-association-values-via-id-or-objects/127356/1 "2008-01-28T16:03:14Z")

</div>

Hi there,

I’ve got a question about best practice/preferred method of setting up  
an association. I have a User model which has and belongs to many  
interests.

From playing about with the console I know I can go…

interests = Interests.find([1,2,3,4])  
user = User.new(:interests=\>interests)  
…or…  
user = User.new(:interest\_ids=\>[1,2,3,4,5])

and similarly on existing objects

user.interest\_ids = [1,2,3,4]  
or user.interests = [interest\_obj\_a, interest\_obj\_b, interest\_obj\_c)

My question is, is there a functional difference between the two, or  
can one freely interchange between setting relations via id or via  
literal objects?

Thanks,

Gavin.

---

<div class="post-metadata">

**Author:** ![casper\_the\_ghost](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/c/58956e/32.png) [@casper\_the\_ghost](https://www.ruby-forum.com/u/casper_the_ghost)\
**Post date:** [January 28, 2008, 11:45pm UTC](https://www.ruby-forum.com/t/setting-association-values-via-id-or-objects/127356/2 "2008-01-28T23:45:33Z")

</div>

removed\_email\_address@domain.invalid wrote:

> Hi there,
> 
> I’ve got a question about best practice/preferred method of setting up  
> an association. I have a User model which has and belongs to many  
> interests.
> 
> From playing about with the console I know I can go…
> 
> interests = Interests.find([1,2,3,4])  
> user = User.new(:interests=\>interests)  
> …or…  
> user = User.new(:interest\_ids=\>[1,2,3,4,5])
> 
> and similarly on existing objects
> 
> user.interest\_ids = [1,2,3,4]  
> or user.interests = [interest\_obj\_a, interest\_obj\_b, interest\_obj\_c)
> 
> My question is, is there a functional difference between the two, or  
> can one freely interchange between setting relations via id or via  
> literal objects?
> 
> Thanks,

There is no difference in the results, where there might be a difference  
is in how many calls to the database each takes. Do which ever is more  
straight forward to start, however. By the time it makes a performance  
difference you may have ditched the HABTM relationship for something  
saner anyway.
