Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails: Update Attribute

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'
like image 215
Ian Ellis Avatar asked Mar 10 '14 18:03

Ian Ellis


People also ask

How do I see changed attributes in Ruby on rails?

Ruby on Rails has solved the changed attributes problem using a Ruby Module named “ Dirty .” The Dirty module “provides a way to track changes in your object in the same way as Active Record does.” This module introduces a new API into your model that allows you to peek and see if a property has changed on your model.

Is update_attribute deprecated in rails 4?

@JoshPinter Hm, update_attribute doesn't seem to be deprecated in Rails 4.2 (it is aliased as update_column ): api.rubyonrails.org/classes/ActiveRecord/… @TončiD. Wow, you are absolutely correct.

When do we need X to happen in Ruby on rails?

We need x to happen, but only when a particular attribute on model y changes. The requirement means you need to watch model y and trigger x if the particular attribute changes. Imagine, for a second, that you work on an e-commerce site. The e-commerce store is a custom Ruby on Rails application with products for sale.

What is the Dirty module in Ruby on rails?

Ruby on Rails has solved the changed attributes problem using a Ruby Module named “ Dirty .” The Dirty module “provides a way to track changes in your object in the same way as Active Record does.”


2 Answers

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.

like image 200
Mike S Avatar answered Nov 03 '22 00:11

Mike S


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.

like image 44
craig.kaminsky Avatar answered Nov 03 '22 01:11

craig.kaminsky