rails: rake populating data
I have a lot of users who has tags, and a lot of posts which has tags.
I want to aut开发者_如何学Pythonopopulate my database when I run rake db:populate. This is my code under lib/tasks:
def make_tags
User.all.each do |user|
5.times do |n|
name = Faker::Company.bs
user.tags.create!(:name => name)
end
end
Micropost.all.each do |micropost|
3.times do |n|
name = Faker::Company.bs
micropost.tags.create!(:name => name)
end
end
However the problem is that usesrs and posts do not share the same tags, because a new tag is created each time. Is there a way to reference to previously created tags by their ids and so that I do not create new tags everytime?
I guess I'd use something along the lines of this:
User.all.each do |user|
5.times do |n|
name = Faker::Company.bs
micropost = Micropost.find(:first, :offset => rand(Micropost.count))
user.tags.create!(:name => name, :micropost => micropost)
end
end
Does that doe what you need? It's demo/test data, right?
Is your micropost associated to a user? If so use that association to set tags for both.
If not, regroup your code, generate a tag, then associate the same tag to a user and to a micropost. Or first tag your users, then iterate through users and put user's tags to microposts.
精彩评论