Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

rails 3.1 active record insert or update

I'm new to rails.

Is there an easy way in active record to pass it a hash of data and if the record exists, update it, and if it doesn't, create it?

data = {}
data["my_id"] = 356345
data["description"] = "test123"

w = Descriptions.new(data)

Ideally if I ran the above it would only ever have 1 record, not multiple records each time I ran it.

like image 300
pablo Avatar asked May 18 '26 04:05

pablo


1 Answers

Assuming you ware wanting the "my_id" bit to be unique you can run

Descriptions.find_or_create_by_my_id(data["my_id"]).update_attributes(data)
like image 167
BananaNeil Avatar answered May 20 '26 00:05

BananaNeil



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!