AntChamberlin
AntChamberlin

Reputation: 53

Rails: how do i change values in table from nil to string inside the rails console?

How would I update a nil value in my rails User database table?

There are three :string fields which are currently nil. And I'm trying to update these fields.

Here is an example of my rails console:

2.4.0 :002 > User.find(1)
  User Load (0.2ms)  SELECT  "users".* FROM "users" WHERE "users"."id" = ? LIMIT ?  [["id", 1], ["LIMIT", 1]]
 => #<User id: 1, email: "[email protected]", created_at: "2017-09-06 11:43:15", updated_at: "2017-09-08 07:42:48", username: nil, first_name: nil, last_name: nil> 
2.4.0 :003 > @user = User.username = ant
NameError: undefined local variable or method `ant' for main:Object
    from (irb):3

What is the correct terminal code I need to update the username: nil, first_name: nil, last_name: nil fields?

Upvotes: 2

Views: 745

Answers (3)

user5683940
user5683940

Reputation:

user = User.find(1)

user.update(username: 'new username attribute goes here', first_name: 'new firstname attribute goes here')

Upvotes: 1

Sebasti&#225;n Palma
Sebasti&#225;n Palma

Reputation: 33420

In your case:

@user = User.username = ant

You're saying, @user is equal to User.username, what at the same time is equal to ant, but what's ant? Rails will try to work with it as a local variable in your current scenario, that's why the message:

NameError: undefined local variable or method `ant' for main:Object

You need to use update, specify each attribute as a "key" and the corresponding new value as the key value, like:

user = User.find(1)
user.update(username: 'new username', first_name: 'new first_name', last_name: 'new last_name')

Upvotes: 2

Mohanraj
Mohanraj

Reputation: 4200

You should be using update or update_attributes method to update AR model with new values to fields/columns.

user = User.find(1)
user.update_attributes(username: 'new username', first_name: 'new first_name')
# OR
user.update(username: 'new username', first_name: 'new first_name')

I think from your question you are getting undefined method ant. Please define ant variable and proceed for the update.

Upvotes: 1

Related Questions