Rails的创建或更新的魔法? [英] Rails create or update magic?
问题描述
我有一类叫做 CachedObject
,其存储的通用序列化对象收录的关键。我想这个类来实现一个 create_or_update
方法。如果一个对象被发现,将更新它,否则会造成一个新的。
I have a class called CachedObject
that stores generic serialised objects indexed by key. I want this class to implement a create_or_update
method. If an object is found it will update it, otherwise it will create a new one.
有没有办法做到这一点在Rails的还是我写我自己的方法?
Is there a way to do this in Rails or do I have to write my own method?
推荐答案
您可以使用 find_or_initialize
或 find_or_create
例如,在轨道4语法:
user = User.find_or_initialize_by(name: "Roger")
user.update(name: "Elmer")
或者
user = User.where(name: "Roger").first_or_initialize
Rails 3的:
Rails 3:
user = User.find_or_initialize_by_name("Roger")
user.update_attributes(name: "Elmer")
如果该记录是新初始化更新
或 update_attributes的
将试图挽救它。
If the record is newly initialised update
or update_attributes
will attempt to save it.
这两种形式接受块:
User.find_or_initialize_by(name: "Roger") do |user|
user.name = "Elmer"
user.save
end
User.where(name: "Roger").first_or_initialize do |user|
user.name = "Elmer"
user.save
end
版本可在<一找到href="http://api.rubyonrails.org/classes/ActiveRecord/Relation.html#method-i-find_or_create_by">api.rubyonrails.org.
这篇关于Rails的创建或更新的魔法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!