Search code examples
ruby-on-railsseeding

How to reference variable ids in Rails seeding


I am manually seeding a databse in the seeds.rb file. I have somthing like the following:

# Users
puts 'SETTING UP DEFAULT USER LOGIN'.colorize( :color => :light_blue, :background => :green )
  chris = User.create(:email => "[email protected]", :password => "asdfasdf", :password_confirmation => "asdfasdf").save!
  teacher1 = User.create(:email => "[email protected]", :password => "asdfasdf", :password_confirmation => "asdfasdf").save!
  student1 = User.create(:email => "[email protected]", :password => "asdfasdf", :password_confirmation => "asdfasdf").save!

Later, I create some songs, and want to assign them to a user:

# Songs
puts 'SETTING UP DEFAULT SONGS'.colorize( :color => :white, :background => :black )
  songs1 = Song.create( title: 't1', content: 'c1', :user_id => chris.index ).save!
  songs2 = Song.create( title: 't2', content: 'c2', user_id: chris.index ).save!
  songs3 = Song.create( title: 't3', content: 'c3', user_id: chris:index ).save!
  songs4 = Song.create( title: 't4', content: 'c4', :user_id => chris.id ).save!

You will notice that the column user_id has three different attempts, all which fail. How do I insert the unique index of the users i created earlier using the variable I assigned them [ chris, t1, and s1]?

The API only hase how to do it manually, or using a loop.


Solution

  • Your problem is the .save! method. It returns boolean, thats why chris, teacher1 and student1 are booleans, not the objects. You don't need save! because create saves the record in the database too, and it returns the object.

    Remove .save! from each line and use .id and you will be good.