0

I'm using seed.rb to start my app.

#seeds.rb, create categories and see if they are saved or not 
categories = Category.create([{name:'name1'},{name:'name2'}, {name: 'name3'} ])
if categories.all?(&:save)
  puts "categories saved"
else
  puts "categories saved failed"
end

In Category Model, I have: before_Save :get_external_resources so I can use nokogiri to fetch something outsite my site

The problem is that when I run rake db:seed, the categories will be saved twice. I tried turn off the before_save, and it only save once. So I guess thatall?(&:save) and before_save have saved this array twice, seperately.

How can I avoid the extra saving? I need to do something before the object get saved and I want to know wheather these objects are saved or not when seeding. How about after_create? I think I'll need to add self.save in methods and may have some validation problem?

Ismael
  • 15,815
  • 6
  • 55
  • 73
cqcn1991
  • 15,169
  • 33
  • 104
  • 180

1 Answers1

0

Well, .create and .save will both save the record, and each will trigger the before_save callback. (if you don't want .create to save, change to Category.new

If you'd like get_external_resources to only execute once, you could do one of:

  1. change it to before_save :get_external_resources, on: :create
  2. change the get_external_resources to only run once
Jesse Wolgamott
  • 39,811
  • 4
  • 78
  • 105
  • `on: :create` works. But I still didn't get the point. It seems like that`.create` triggers a save, and `before_save :get_external_resources` triggers another? – cqcn1991 Jul 21 '13 at 13:12