I'm using the seeds.rb to create some user records:
100.times do
user = User.new
user.username = Faker::Name.first_name
user.email = user.username+"@example.com"
user.save!
end
This works just fine and the users have been created after I ran
db:seeds but what's not working is:
I'm using the seeds.rb to create some user records:
100.times do
user = User.new
user.username = Faker::Name.first_name
user.email = user.username+"@example.com"
user.save!
end
This isn't directly a solution to your problem, but...
Is this for testing? If so, I recommend using factories, not seeds.
seeds.rb is for application seed data (such as tables of countries or
shipping rates), not what you're apparently doing here.
...but why do your tests need 100 records to begin with? Normally, you
should just call the factory within each test to create the (1 or 2)
records you need for that test.
Please quote when replying; otherwise, it gets difficult to follow the
discussion.
So this is actual production data?
Yes, it is.
It's not appropriate to use an after_create for this sort of thing, I
think. In your 100.times block, just create a comment when you create
each user.
Makes sense for comments but there but there's stuff like attributes
etc. which needs to be created even when a user is created from the web
interface. Do you know why the code above doesn't work?
jojo, now i see what you are doing, is just that i didnt saw the after create the first time, you are using the self reserved word indeed to refer to the created user in the after create, have you tried that before? why not put the function in the loop after the user.save ?
sorry now i see it makes no sense, i understood that this is all in your seed.rb and both functions will only be used once and i was suggesting this
100.times do
user = User.new
user.username = Faker::Name.first_name
user.email = user.username+“@example.com”
user.save!
write_comments(user) <=== this could be in your controller create action
end
protected
def write_comments(user)
comment = Comment.new
comment.text = “some text”
comment.user = user
comment.save!
end
After paying more attention to your comment i notice you want the write_comments to be in your model in production, and my suggestion made no sense.