Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you update attributes in an instance method in a rails model without using different variable names?

I would like to update attributes in an instance method in rails without being forced to change the parameters being passed in so that I can advantage of rails automatic attributes. Here is an example.

Ideal:

status = "some_new_status"
person.update(status)

class Person < ActiveRecord::Base
  def update(status)
    self.status = status
  end
end

What I have to do now:

class Person < ActiveRecord::Base
  def update(new_status)
    self.status = new_status
    self.save
  end
end

I understand in this example it doesn't much matter. But when I have complicated update methods, it would be a lot cleaner if I could eliminate some of that code.

like image 983
David Groff Avatar asked Aug 17 '11 12:08

David Groff


People also ask

What is Active Record in Ruby on Rails?

Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.

What is Activemodel?

Active Model is a library containing various modules used in developing classes that need some features present on Active Record.

What does update do in Rails?

Updates an object (or multiple objects) and saves it to the database, if validations pass. The resulting object is returned whether the object was saved successfully to the database or not.

Does Update_attributes call save?

the difference between two is update_attribute uses save(false) whereas update_attributes uses save or you can say save(true) .


1 Answers

You should use builtin Rails methods:

@person.update_attribute(:status, "Some Value") #no callback triggered nor validation

@person.update_attributes(:status => "Some Value") #can pass multiple values

Or to keep your short syntax

def update(status)
  update_attribute(:status, status)
end

Update_attribute doc.

Update_attributes doc.

like image 137
apneadiving Avatar answered Sep 18 '22 00:09

apneadiving