rails 3.1 active record insert or update

与世无争的帅哥 提交于 2019-12-23 19:08:19

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!