nested resources rails has and belongs to many

230 views Asked by At

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?

1

There are 1 answers

1
Vrushali Pawar On BEST ANSWER

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