我是编程新手,并且一直在尝试使用Faker为一个简单的书签应用程序制作一些种子数据。主题属于用户,书签属于主题,因此我尝试使用具有user_id的主题制作种子数据。最初,我只是放了user.sample,但是我需要拥有该主题的用户的user_id,并且书签需要它所属主题的topic_id。您可以在下面看到我的一项努力。你是怎么做的?这是我的种子数据:
require 'faker'
#create users
10.times do
user = User.new(
name: Faker::Name.name,
email: Faker::Internet.email,
password: 'helloworld'
)
user.save!
end
users=User.all
# create bookmarks
30.times do
Bookmark.create(
topic_id: topic.sample,
url: Faker::Internet.url
)
end
bookmarks = Bookmark.all
# create topics
10.times do
Topic.create(
name: Faker::Name.name,
user_id: user.sample
)
end
topics= Topic.all
#create admin
admin = User.new(
name: 'admin',
email: 'admin@example.com',
password: 'helloworld'
)
admin.save
puts 'Seed Finished'
puts "#{users.count} users created"
puts "#{topics.count} topics created"
puts "#{bookmarks.count} bookmarks created"
这是我的架构:
ActiveRecord::Schema.define(version: 20150118002825) do
create_table "bookmarks", force: true do |t|
t.string "url"
t.integer "topic_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "likes", force: true do |t|
t.integer "user_id"
t.integer "bookmark_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "topics", force: true do |t|
t.string "name"
t.integer "user_id"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "users", force: true do |t|
t.string "name"
t.string "email"
t.string "password_digest"
t.datetime "created_at"
t.datetime "updated_at"
end
end
以下是我的模特:
class Topic < ActiveRecord::Base
belongs_to :user
has_many :bookmarks
end
class User < ActiveRecord::Base
has_secure_password
has_many :topics
end
class Bookmark < ActiveRecord::Base
belongs_to :topics
has_many :likes
end