简体   繁体   English

rails 3.1活动记录插入或更新

[英]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. 理想情况下,如果我运行上述内容,每次运行时只会有1条记录,而不是多条记录。

假设您想要“my_id”位是唯一的,您可以运行

Descriptions.find_or_create_by_my_id(data["my_id"]).update_attributes(data)

An ActiveRecord object in Rails retains its identity in the ID parameter. Rails中的ActiveRecord对象在ID参数中保留其标识。 If the ID is set, Rails will know to update the record in the database with that ID. 如果设置了ID,Rails将知道使用该ID更新数据库中的记录。

save is, in fact, the primary way to create, update, or in any way save an object to the database. 实际上, save是创建,更新或以任何方式将对象保存到数据库的主要方式。 Other methods like update_attributes are just sugar that use save at their core. update_attributes这样的其他方法只是在其核心使用save糖。

Yes,There are many good things you will get ModelName.find_or_create_by_name("Summer") 是的,你会得到许多好东西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. 但是如果你在更新的save方法中传递Id,如果没有传递id,它将create数据。

Always, Primary Key in Rails should be "id" but you used "my_id" that may also be the problem. 总是,Rails中的主键应该是“id”但你使用的“my_id”也可能是问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM