Gibson
Gibson

Reputation: 2085

How to create multiple records from array in Rails Console

I want to create 7 categories in production, so I have an array for them:

categories = ["Industrial & Loft","Nórdico","Moderno","Clásico","Contemporaneo","Exótico","Rustico","Landing"]

I want to loop through the array in rails console, and create a new category for each of the items, but this wont work:

categories.each { |category| category.new}

It says: NoMethodError: undefined method `new' for "Industrial & Loft":String

What am I missing? Thanks

Upvotes: 1

Views: 2000

Answers (1)

MWeber
MWeber

Reputation: 613

If Category is one of your model classes, then you need to capitalize it and then assign the value of the categories item to one of the model elements (such as name in my example):

categories.each { |c| Category.new(name: c)}

Edit: But remember that "new" doesn't save a record, so you might want to use create, which is new & save combined:

categories.each { |c| Category.create(name: c)}

Upvotes: 3

Related Questions