2

I have a ProductsColor model. Given a params hash, is there a way to set an existing record's attributes with one method without saving it? Similar to how ProductsColor.new(params) would instantiate an object and set its attribute to the ones in the params hash, I want to set attributes of an existing record without saving it like so:

    params = {name: "hey"}

    p = ProductsColor.find(1)
    p.something(params) # does not save to the database, but does set the value of the params to p in memory
    p.name # "hey"
    p.save # <-- now it saves permanently
user2864740
  • 60,010
  • 15
  • 145
  • 220
bigpotato
  • 26,262
  • 56
  • 178
  • 334

3 Answers3

6

You can do it this way:

p = ProductsColor.find(1)
p.assign_attributes(params)

It will not be saved

Diego
  • 848
  • 7
  • 16
1

What you are looking for is:

assign_attributes

which will update the attributes without saving the record.

Check this answer for more info:

Rails update_attributes without save?

Community
  • 1
  • 1
Jorge de los Santos
  • 4,583
  • 1
  • 17
  • 35
0

There is a active record method called assign_attributes to assign the attributes for active record object. It should be something like below,

products_color = ProductsColor.first
products_color.assign_attributes({name: 'New name'})
Mohanraj
  • 4,056
  • 2
  • 22
  • 24