Ruby On Rails Classroom image

Neha  Jaggi / Professional / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  First|1 | 2|
Lessons:-Creating User Objects

You may have noticed that the new user object had nil values for the id and the magic columns created_at and updated_at attributes. Let’s see if our save changed anything:

 

>> user
=> #<User id: 1, name: "Michael Hartl", email: "mhartl@example.com",
created at: "2011-12-05 00:57:46", updated at: "2011-12-05 00:57:46">

 

We see that the id has been assigned a value of 1, while the magic columns have been assigned the current time and date.6 Currently, the created and updated timestamps are
identical; we’ll see them differ in Section 6.1.5. 

                As with the User class in Section 4.4.5, instances of the User model allow access to their attributes using a dot notation:7

 

>> user.name
=> "Michael Hartl"
>> user.email
=> "mhartl@example.com"
>> user.updated at
=> Tue, 05 Dec 2011 00:57:46 UTC +00:00

 

As we’ll see in Chapter 7, it’s often convenient to make and save a model in two steps as we have above, but Active Record also lets you combine them into one step
with User.create: 

 

>> User .create (name:   "A Nother" , email:   "another@example.org")
#<User id: 2, name: "A Nother", email: "another@example.org", created at:
"2011-12-05 01:05:24", updated at: "2011-12-05 01:05:24">

>> foo = User.create(name: "Foo", email:  "foo@bar.com")
#<User id: 3, name: "Foo", email: "foo@bar.com", created at: "2011-12-05
01:05:42", updated at: "2011-12-05 01:05:42">

 

Note that User.create, rather than returning true or false, returns the User object itself, which we can optionally assign to a variable (such as foo in the second command above). 

              The inverse of create is destroy:

 

>> foo.destroy
=> #<User id: 3, name: "Foo", email: "foo@bar.com", created at: "2011-12-05
01:05:42", updated at: "2011-12-05 01:05:42">
 

 

 

Oddly, destroy, like create, returns the object in question, although I can’t recallever having used the return value of destroy. Even odder, perhaps, is that the destroyed object still exists in memory: 

 

>> foo
=> #<User id: 3, name: "Foo", email: "foo@bar.com", created at: "2011-12-05
01:05:42", updated at: "2011-12-05 01:05:42">

 

How do we know if we really destroyed an object? And for saved and non-destroyed objects, how can we retrieve users from the database? It’s time to learn how to use Active
Record to find user objects. 

 
 
 
image
Neha  Jaggi

Skills    Ruby On Rails

Qualifications :- High School - , College/University - Graphic Era Hill University, Dehradun, College/University - ,
Location :-Dehradun,Dehradun,UTTARAKHAND,India
Description:-

Experienced Software Developer with a demonstrated history of working in the Information Technology and services industry. Skilled in Web Technologies (Ruby on Rails, PostgreSQL, php, Laravel and AJAX). 


Explore
 

  Students (0)