Ruby On Rails Classroom image

Anil  Bist / Professional / Web Technology

 
To post your Question Join Classroom
 
Lesson Topics's No:-  ||
Lessons:- Updating User Objects

 Updating User Objects


Once we’ve created objects, we often want to update them. There are two basic ways to do this. First, we can assign attributes individually, as we did in Section 4.4.5:

 

>> user                                  # Just a reminder about our user's attributes
=> #<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">

>> user.email =   "mhartl@example.net"
=> "mhartl@example.net"
>> user.save
=> true

 

Note that the final step is necessary to write the changes to the database. We can see what happens without a save by using reload, which reloads the object based on the database information:  

 

>> user.email
=> "mhartl@example.net"
>> user.email =   "foo@bar.com"
=> "foo@bar.com"
>> user.reload.email
=> "mhartl@example.net"

 

Now that we’ve updated the user, the magic columns differ, as promised in Section 6.1.3: 

>> user.created at
=> "2011-12-05 00:57:46"
>> user.updated at
=> "2011 -12-05 01:37:32"

 

The second way to update attributes is to use update_attributes: 

>> user.update attributes  ( name:    "The Dude", email:  "dude@abides.org")
=> true
>> user.name
=> "The Dude"
>> user.email
=> "dude@abides.org"

 

The update_attributes method accepts a hash of attributes, and on success performs both the update and the save in one step (returning true to indicate that the save went through). It’s worth noting that, once you have defined some attributes as accessible using attr_accessible (Section 6.1.2), only those attributes can be modified using update_attributes. If you ever find that your models mysteriously start refusing to update certain columns, check to make sure that those columns are included in the call to attr_accessible. 

 
 
 
image
Anil  Bist

Skills    Ruby On Rails

Qualifications :- High School - SLV, College/University - Graphic Era Deemed Univ University,
Location :-Dehradun,Dehradun,Uttarakhand,India
Description:-

I started my Professional Journey in 2006 with one of the Web Development Company in Bangalore and my 1st framework was "Ruby on Rail" as Web development and delivered around 5+ Projects using this platform. Then came another dimension as JEE/Sturst framework, Gradually I realized that I want to build something on my own and give my passion and energy on creating something different a
Explore

 

  Students (0)