Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Seeding HABTM associations

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?

like image 489
Nick5a1 Avatar asked Jul 07 '12 19:07

Nick5a1


2 Answers

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']))
like image 68
Matzi Avatar answered Sep 28 '22 17:09

Matzi


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)
like image 23
CBear Avatar answered Sep 26 '22 17:09

CBear