Stoob
Stoob

Reputation: 121

Seeding a rails model with an array in rails

I understand that the answer may be in similar answers that I've read but I do not yet have the knowledge power to draw a solution from them.

I'm trying to seed a column in a rails model with an array:

["N1", "N2", "N3", "N4", "N5", etc ]

Each value will represent a new line (or entry? not sure of the correct terminology) in the database column.

Currently, similar to what has been suggested in a similar posts, I'm using:

[above array].each do |pc| 
    Postcodes.create!({ pcode => pc}) 
end

But I'm getting the following error:

NameError: uninitialized constant Postcodes

I've tried un-pluralising the model name and also un-capitalising but this does not seem to help.

db:schema:

ActiveRecord::Schema.define(version: 20151211095938) do

create_table "users", force: :cascade do |t|
t.string   "first_name"
t.string   "last_name"
t.string   "email"
t.string   "password_digest"
t.datetime "created_at",      null: false
t.datetime "updated_at",      null: false

end

end

Model:

class Postcode < ActiveRecord::Base
end

Upvotes: 0

Views: 164

Answers (1)

spickermann
spickermann

Reputation: 106792

Your model is names Postcode, not Postcodes (not the plural s). The following should work:

codes = ["N1", "N2", "N3", "N4", "N5"]

codes.each do |code|
  Postcode.create!(pcode: code) 
end

Upvotes: 2

Related Questions