in Programming, Uncategorized

Always save after updating a record within Rails console

You should always remember to do one of two things. save or use a bang method when working with records inside of Rails Console.

I had the following:

p = Product.first
p.category_id = 1

This is going to change the record within the console session, but this will not actually save the changes. You must run,

to save the changes.

Bang method

A common way to create a record from within the rails console is to do the following

p = 'Settlers of Catan', price: '14.99', category_id: 3)

If you wanted to create the record within one line, then you should use create!

p = Product.create!(name: 'Settlers of Catan', price: '14.99', category_id: 3)

That’s one less line to type.

Write a Comment