问题
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.
回答1:
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)
回答2:
An ActiveRecord object in Rails retains its identity in the ID parameter. If the ID is set, Rails will know to update the record in the database with that ID.
save is, in fact, the primary way to create, update, or in any way save an object to the database. Other methods like update_attributes are just sugar that use save at their core.
Yes,There are many good things you will get ModelName.find_or_create_by_name("Summer")
But If you pass Id in save method that will be update and if id is not passed it will create data.
Always, Primary Key in Rails should be "id" but you used "my_id" that may also be the problem.
来源:https://stackoverflow.com/questions/9373540/rails-3-1-active-record-insert-or-update