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?

Nick5a1
  • 917
  • 3
  • 15
  • 28

2 Answers2

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']))
Matzi
  • 13,770
  • 4
  • 33
  • 50
  • 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'])) – J Edward Ellis Nov 03 '16 at 22:47
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)
CBear
  • 31
  • 3