Question

I have two relationships namely, User and Branch wherein there is a many to many relationship between them(I used HABTM in their models) and they are joined by a table called branches_users.

An entry is created in the branches and in the join table when I use:

User.find(1).branches.create({"branch_id" => 12312, "branch_name" => "sample"})

but, when I use

object = User.find(1).branches.new({"branch_id" => 12312, "branch_name"=> "sample"})

and then use

object.save

The entry is created only in the branches table, so when I use User.find(1).branches the entry doesn't come up. I need a workaround for this, I need to use new instead of create since I have to do some manipulations before I save.

Was it helpful?

Solution

Here is an example how to do it:

object = Branch.new({"branch_id" => 12312, "branch_name"=> "sample"})
object.users << User.find(1)
object.save

Before the save you can manipulate what ever you want. It will save the relationship in the correct way.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top