HABTM - how to insert join row when associated rows exist

I have successfully used HABTM to create a many-to-one-to-many set of
rows in one step. Now, if two objects I want to associate already exist,
how do I create the join row? The Agile book mentions the
‘push_with_attributes’ method. The text says this method is useful for
adding additional attributes to the join row (in the example a ‘read_at’
timestamp). I only require a simple two-key join row - is
‘push_with_attributes’ the way to go?

-Lindsay

Lindsay B. wrote:

many-to-one-to-many set of rows

should read ’ one-to-many-to-one rows’

-Lindsay

It’s OK, I figured it out.

-Lindsay

Please end your monolog in a proper way by stating your solution.

A bug in my model’s validation prevented the join row from being
created. No solution as such.

  • Lindsay

push with attributes is not what you want to use. that’s for when you
have
additional columns in your join table other than the two id columns for
the
joined tables.

example of what you want to do:

assumiing a habtm between foo and bar (using table bars_foos as join
tabled)

foo = Foo.find(1)
bar = Bar.find(1)

foo.bars << bar

or you could do bar.foos << foo, same results

this will create the association in the join table.

http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html#M000533

Chris

Lindsay B. wrote:

It’s OK, I figured it out.

-Lindsay

Please end your monolog in a proper way by stating your solution.

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs