0

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, "sample@foo.bar" <- OK
  2. User.find_by(:id => 1).update_attributes :email => "sample@foo.bar" <- this return to me false

and is there any way to update it by:

@foo = User.find_by(:id => 1)
foo.email = "sample@foo.bar"
foo.save
matDobek
  • 757
  • 1
  • 5
  • 12
  • in this thread you could find you answer [here](http://stackoverflow.com/questions/2778522/rails-update-attribute-vs-update-attributes) – rony36 May 04 '13 at 10:46
  • btw `foo.email` should be `@foo.email` and `foo.save` should be `@foo.save` – drhenner May 04 '13 at 16:17

3 Answers3

1

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 = "sample@foo.bar"
@user.save

# or update_attributes which can update multiple attributes at once:
@user.update_attributes(email: "sample@foo.bar", 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, "sample@foo.bar")
mind.blank
  • 4,820
  • 3
  • 22
  • 49
0

you can simply update record by, User.find(:id=>1).update_attribute(:email=>'sample@foo.bar') as update_attributes is use to update all attributes.

Kushal
  • 218
  • 2
  • 12
0

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

First Approach would be:

ex. user = User.find(1)
    user.attributes = {
        :email => "sample@foo.bar"
     }
    user.save

Second approach would be:

ex. 
    user = User.find(1)
    user.update_attributes{:email => "sample@foo.bar"}

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

ex.
 def update
  user = User.find(params[:user])
  user.update_attributes
 end 
AllenC
  • 2,754
  • 1
  • 41
  • 74