On Dec 14, 10:14 am, Marnen Laibow-Koser <li...@ruby-forum.com> wrote: > ppgeng...@prevailhs.com wrote in post #968310: > [...] > > > Keep in mind that in this case you don't want to do: > > > @person = Factory(:person) > > @address = Factory(:address) > > @person.addresses << @address > > > Because the second line will generate another, unneeded Person object. > > Hold it. If there's a habtm relationship between Person and Address, > then Addresses shouldn't even have a person_id. OTOH, if there isn't a > habtm relationship, then the << operation is unnecessary (and I think > it's a syntax error). > > So...which is it?
In his original example Address has a person_id field so I was assuming a has_many relationship, not a HABTM. However, though I'd want to reflect on it further, I'm pretty sure it doesn't change anything here as long as you deal with the relationship name everywhere and not the ID fields; Rails will just do The Right Thing (tm) and add/remove records in the join table appropriately. The << is necessary in the second example to be comparable to his original example where he wanted to create an @person object, then create an @address object and have them linked; the @address at first will point to a different Person object than @person, so using the << on the collection will add it (i.e. it will set person_id on @address to @person.id). It does work BTW, I just tested it again in console to be sure (and its listed at the top of the added methods here: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_many, and if we care about the HABTM here: http://apidock.com/rails/ActiveRecord/Associations/ClassMethods/has_and_belongs_to_many). I think maybe what you're pointing out though, is that he could just do: @address = Factory(:address) and then use @address.person? If that's adequate then that's definitely cleaner (and quicker and more robust). However, what I read from the OP is that he has a need to create a Person object first, configured a specific way (although he didn't have any particular factory overrides, so maybe this is an incorrect assumption?). ~After~ that object is created he needs an Address that is linked to it. As such he either needs to 1) create the Address object with a stub Person, then associate with the one he wants afterwards (suboptimal, the usage of <<) or 2) pass in the Person object to the Address factory to link at creation time (preferred, AFAIK). \Peter -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to rubyonrails-t...@googlegroups.com. To unsubscribe from this group, send email to rubyonrails-talk+unsubscr...@googlegroups.com. For more options, visit this group at http://groups.google.com/group/rubyonrails-talk?hl=en.