Rails - Seeding HABTM associations
Asked Answered
D

2

7
Equipment.create(name: "Room to run")
Equipment.create(name: "Pull-up bar")
Workout.create(
  description: "Do 100 pull-ups then run 5km",
  :equipment => Equipment.where(:name => 'Pull-up bar'))

Equipment and Workouts have a HABTM relationship. The above seeds code works but how can I also assign a second equipment association at the same time as the first?

Deathtrap answered 7/7, 2012 at 19:14 Comment(0)
C
7

In the where condition, you can use array:

Equipment.create(name: "Room to run")
Equipment.create(name: "Pull-up bar")
Workout.create(
  description: "Do 100 pull-ups then run 5km",
  :equipment => Equipment.where(:name => ['Pull-up bar', 'Room to run']))
Curtilage answered 7/7, 2012 at 19:25 Comment(1)
The use of equipment in this example is unfortunate. The noun equipment is both singular and plural, which hides an important detail. If we were talking about dogs the example would look like: :dogs => Dog.where(:name => ['Fido', 'Butch']))Kelula
F
3

In the seeds file this simple list worked with products and categories(HABTM) relationship. It's super literal and effective.

Product.find(1).categories << Category.find(4)
Product.find(1).categories << Category.find(5)
Product.find(2).categories << Category.find(5)
Fortnight answered 14/12, 2015 at 18:18 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.