irishcoder
irishcoder

Reputation: 191

Creating Rails Seed data with foreign keys

I'm looking to create seed data that follows the foreign key constraints indicated.

I'm getting the message "undefined method 'create' for nil:NilClass"

My Commands:

rails g model user login:string password:string
rails g model account gender:string age:integer first_name:string last_name:string user:references

seeds.rb

User.delete_all
Account.delete_all

Attempt 1 to seed associated tables

@Jared = User.create [{login: "Jared", password: "password2"}]
@Jared.first.account.create([{gender: "male", age: 99, first_name: "Irish", last_name: "Coder"}])

Attempt 2 to seed associated tables

acct = Account.create [{gender: "male", age: 99, first_name: "Irish", last_name: "Coder"}]
@Jared.account = acct

user.rb

class User < ActiveRecord::Base
  has_one :account
end

account.rb

class Account < ActiveRecord::Base
  belongs_to :user
end

Upvotes: 1

Views: 3415

Answers (1)

Sully
Sully

Reputation: 14943

@Jared = User.create [{login: "Jared", password: "password2"}]
@Jared.first.account.create([{gender: "male", age: 99, first_name: "Irish", last_name: "Coder"}])

where this part is nil

@Jared.first

try:

defaults = User.create(login: "Jared", password: "password2")
User.create{login: defaults.login, password: defaults.password, gender: "male", age: 99, first_name: "Irish", last_name: "Coder"}

Upvotes: 1

Related Questions