5

Google is seriously failing me right now. All I need to do is update one attribute, setting a user to admin, from the Heroku rails console.

I can't find a single simple answer. What I've been trying is:

Record.update_attribute(:roles_mask, "1")

Where record is the correct record.

'undefined method 'update attribute''

I can't just type Record.roles_mask = 1?

EDIT.

I used Record, and I shouldn't have done that in the example. What I've done is exactly this:

ian = User.where(:id => '5')

ian.update_attribute(:roles_mask, '1')

Error: undefined method 'update_attributes'
Ian Ellis
  • 541
  • 6
  • 19

3 Answers3

10

The problem is that using the .where function creates a relation, rather than finding the record itself. Do this:

ian = User.find(5)
ian.update_attribute(:roles_mask, '1')

Or if you want to use .where then you could do this:

ian = User.where(:id => 5)
ian.first.update_attribute(:roles_mask, '1')

EDIT

See this answer for details about why this is happening.

Community
  • 1
  • 1
Mike S
  • 11,329
  • 6
  • 41
  • 76
  • 1
    As a side note for future google searches, another issue was that the variable I was using was protected. I had to allow mass-assignment. attr_accessible :roles_mask. Thank you for your response. – Ian Ellis Mar 10 '14 at 18:37
3

To use update_attribute (or update_attributes), you need to call that from an instance and not the class.

rails c> rec = Record.find(1)
rails c> rec.update_attribute(:att, 'value')
rails c> rec.update_attributes(att: 'value', att2: 'value2')

I would think that should take care of your issue.

craig.kaminsky
  • 5,588
  • 28
  • 31
  • Doesn't work. I have ian = User.where(:id => '5') ian.update_attribute(:roles_mask, '1') error: undefined method 'update_attribute' Also, thank you for your response. For the record, I am only trying to update 1 record. – Ian Ellis Mar 10 '14 at 18:28
  • The problem there is that where() returns an ActiveRecord relation. Try either of the following: ian = User.find(5) or ian = User.where(id: 5).first ... ignore. Just saw that @Mike Slutsky said as much. – craig.kaminsky Mar 10 '14 at 18:57
1

Where clause return a array and you are trying to make update query on array, that's why you got error.

you should try to find out first record

ian = User.where(:id => 1).first
or
ian = User.find(1)
or
ian = User.find_by_id(1)

now your update query will work.

ian.update_attribute(:roles_mask, '1')
uma
  • 2,932
  • 26
  • 20