-1

Sorry for the generic title, but I'm not sure how to phrase it better at the moment. I finally had some time to start picking up rails again and came across this issue as I was building my models:

Essentially I have a parent resource that has two nested resources. The parent can have many of each child resource and each child resource can have one parent. This part is working fine. The difficulty comes when I want to have a has_and_belongs_to_many relationship between the two child resources. I'm not sure how to implement this so that when I create a new Child 1, I can associate it with multiple existing Child 2's.

Imagine this like I have a User, Dog, and Walk models. The User is the parent, but each dog will have gone on many walks and each walk may have many dogs in it.

I've been looking for any tutorials for this part and have not had much luck. Can someone point me in the direction of a potential solution?

sulimmesh
  • 693
  • 1
  • 6
  • 23
  • this is many to many relationship and for this ypu can go use either has_many through or has_and_belongs_to_many – Vrushali Pawar Jun 09 '15 at 05:11
  • Yes, I'm trying to use has_and_belongs_to_many for this, but I'm trying to resolve how to create new instances of walks given that both dogs and walks belong to a user. Also how would this look to the user in a new walk form? How can I give the user the option to add multiple dogs to a walk, etc – sulimmesh Jun 09 '15 at 05:15

1 Answers1

0

dog.rb

has_and_belongs_to_many :walks

walk.rb

has_and_belongs_to_many :dogs

Creation of object:

@walk = Walk.last
@dog = Dog.last
@walk.dogs << @dog

For this association, you will be having a join table as dogs_walks who won't have a model and will have attributes as dog_id, walk_id and it won't have id as primary key

Vrushali Pawar
  • 3,753
  • 1
  • 13
  • 22
  • Thanks that last line is what I was needing. One last thing though: how can I a user fill a form to invoke that last line? For instance I want the user to decide which dog_id to assign to a given walk_id. How might I put that in a form? – sulimmesh Jun 09 '15 at 06:42