1

私はプログラミングが初めてで、Faker を使用して簡単なブックマーク アプリ用のシード データを作成しようとしています。トピックはユーザーに属し、ブックマークはトピックに属しているため、user_id を持つトピックでシード データを作成しようとしています。本来はuser.sampleだけ入れたのですが、トピックを所有しているユーザーのuser_idが必要で、ブックマークには所属するトピックのtopic_idが必要です。ここで私の努力の1つを以下に見ることができます。これをどのように行うのですか?ここに私のシードデータがあります:

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
4

0 に答える 0