3

Are there any other ways to set attributes for models in Rails other than using attribute=?

For example, is there something like set_attribute(name, value)?

user = User.new
user.set_attribute(:name, 'Jack')
user.set_attribute(:surname, 'The Ripper')
user.save

# instead of
user.name = 'Jack'
user.surname = 'The Ripper'

2 Answers 2

3

looking to the AR source we can find

# File activerecord/lib/active_record/persistence.rb, line 208
def update_attributes(attributes, options = {})
  # The following transaction covers any possible database side-effects of the
  # attributes assignment. For example, setting the IDs of a child collection.
  with_transaction_returning_status do
    self.assign_attributes(attributes, options)
    save
  end
end

so you can use assign_attributes(attributes, options) to set attributes without saving

Also if you want to set attribute by name without calling a method directly you can use user.send(:name=, 'Jack') instead of user.set_attribute(:name, 'Jack')

Sign up to request clarification or add additional context in comments.

Comments

2

There is a write_attribute method. It should be what you're looking for.

EDIT

You can use update_attributes if you want to update many attributes at once.

6 Comments

Thanks for the answer, lucapette. Is there a similar method which allows to assign several attributes at once? Something like write_attributes.
update_attributes method is available for immedeately attributes update(with saving) and here is attributes= also, which just modifying original object without saving
@Shamaoke As 4pcbr has said if you want to write many attributes at once you can use update_attributes.
According to ApiDock, attributes= is outdated. update_attributes doesn't fit well since it saves attributes and also, I think, its purpose still not to set but to update.
@Shamaoke I see. So you just want to set a lot of attributes a time. Whitout persisting them?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.