The Rails console is an interactive tool for running Ruby code that is able to access our app’s model code (among other things). We will use it to explore the kinds of things we can do with our model in Ruby on Rails. The Ruby code we will write in the console is the same sort of code we might write, for example, in our app’s controller methods to enable our app to perform various functions.
create
method.new
constructor and save
method.create
Launch Rails console:
rails console
Create new Person
object and save to database via create
:
Person.create(first_name: 'Homer', last_name: 'Simpson', height_inches: 60, weight_lbs: 241)
INSERT
command creates new row in people
table.Exit Rails console:
exit
Inspect people
table:
psql --command="SELECT * FROM people" app_development
new
/save
Launch Rails console:
rails console
Create new (unsaved) Person
object via new
:
marge = Person.new
Person
object (#<Person:0x000000010702cf08
), but no SQL commands run.Set object’s attribute values:
marge.first_name = "Marge"
marge.last_name = "Simpson"
marge.height_inches = 102
marge.weight_lbs = 139
Save object to database:
marge.save
INSERT
command creates new row in people
table..Exit Rails console:
exit
Inspect people
table:
psql --command="SELECT * FROM people" app_development