matDobek
matDobek

Reputation: 777

Updating database, what options do I have?

I'm a beginner in Rails, and I want to know how can I update my database?(I'd like to know all possible options to do it).

I got simple table called USERS, where I got :name and :email attributes.

As i read I can update my :email by:

  1. User.find_by(:id => 1).update_attribute email, "[email protected]" <- OK
  2. User.find_by(:id => 1).update_attributes :email => "[email protected]" <- this return to me false

and is there any way to update it by:

@foo = User.find_by(:id => 1)
foo.email = "[email protected]"
foo.save

Upvotes: 0

Views: 87

Answers (3)

AllenC
AllenC

Reputation: 2754

Hi there are two ways to update your data using ActiveRecord update.

First Approach would be:

ex. user = User.find(1)
    user.attributes = {
        :email => "[email protected]"
     }
    user.save

Second approach would be:

ex. 
    user = User.find(1)
    user.update_attributes{:email => "[email protected]"}

You can also update using "update method" on your specific controller:

ex.
 def update
  user = User.find(params[:user])
  user.update_attributes
 end 

Upvotes: 0

mind.blank
mind.blank

Reputation: 4880

update_attribute skips validations. So update_attributes is returning false since it's not passing some validation. Double check your User model validations and also make sure that under attr_accessible you've added email:

class User < ActiveRecord::Base
  attr_accessible :email, :name # etc
end

Also with find you don't have to specify the attribute, just use an integer:

@user = User.find(24) # this will find a User with the ID of 24

@user.email = "[email protected]"
@user.save

# or update_attributes which can update multiple attributes at once:
@user.update_attributes(email: "[email protected]", name: "Bob")

# or update_attribute which skips validations and can only update 1
# attribute at a time. Only used for specific situations:
@user.update_attribute(:email, "[email protected]")

Upvotes: 1

Kushal
Kushal

Reputation: 218

you can simply update record by, User.find(:id=>1).update_attribute(:email=>'[email protected]') as update_attributes is use to update all attributes.

Upvotes: 0

Related Questions