Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting ID of object when importing seed data from JSON file in Rails

I'm importing objects in my seeds file from a json file like this:

[
{
    "email":"[email protected]",
    "id":1,
    "league_id":1,
    "name":"Slim Jims are good for the heart...OH YEAH!",
    "owner":"Jon"
},
{
    "email":"[email protected]",
    "id":2,
    "league_id":1,
    "name":"The Bucket List",
    "owner":"Robert"
}
]

my seeds file is:

require 'json'
Team.delete_all
JSON.parse(open("#{Rails.root}/doc/teams.json").read).each do |stuff|
   Team.create(stuff)
end

My problem is that it assigns some random id instead of the id from the json file.

like image 779
cbass Avatar asked Feb 21 '23 01:02

cbass


1 Answers

For anyone wondering, you can do this by using this syntax instead of create:

JSON.parse(open("#{Rails.root}/doc/teams.json").read).each do |stuff|
    team = Team.new(stuff)
    team.id = stuff['id']
    team.save!
end
like image 104
gbsice Avatar answered May 04 '23 19:05

gbsice