Search code examples
ruby-on-railsrubyruby-on-rails-3has-and-belongs-to-manyseed

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?


Solution

  • 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']))