user2784630
user2784630

Reputation: 806

How can I create the same record X amount of times in my seed data?

I'm new to Rails (4.0.0) and Ruby (2.0.0) and wanted to know how to give each user the same book ten times. So first, I create my three Users:

user1 = User.create(name: "Fred")
user2 = User.create(name: "Bob")
user3 = User.create(name: "Ron")

Now I want to give all three users one book ten times to test my application. So I start out like this:

book = Book.create(title: "My Book")

After I get lost on how to do the each and assigning the users. Do you know how to? Mass assignment security doesn't matter in this situation, just need the data for view testing.

Upvotes: 2

Views: 1298

Answers (3)

Mikhail Nikalyukin
Mikhail Nikalyukin

Reputation: 11967

User.all.find_each do |user|
  10.times { |i| user.books << Book.create!(title: "Book number #{i}") }
end

Upvotes: 7

usha
usha

Reputation: 29349

Use without_protection if you want to skip the mass_assignment protection

[user1, user2, user3].each do |user|
  10.times do |i|
    Book.create!({title: "Book ##{i}"}, :without_protection => true)
  end
end

Upvotes: 3

Damien MATHIEU
Damien MATHIEU

Reputation: 32629

This will look through all your users, then loop 10 times for each, creating a book each time (therefore creating 10 books).

[user1, user2, user3].each do |user|
  10.times do |i|
    Book.create!(title: "Book ##{i}")
  end
end

Upvotes: 5

Related Questions