如果存在则更新,否则什么也不做?

时间:2013-03-20 21:06:25

标签: ruby-on-rails ruby

当且仅当模型存在时,我正在尝试更新模型的值。如果没有,我什么都不做。搜索似乎只返回更新或创建问题/答案,但我不想创建。

我知道我可以用一个简单的方法来做到这一点:

found = Model.find_by_id(id)
if found
  update stuff
end

但是,我觉得有一种方法可以在一次调用中执行此操作,而无需分配任何临时本地值或执行if。

如果不存在嘈杂错误,如何编写rails调用来更新记录?

最新的Rails 3.x

4 个答案:

答案 0 :(得分:8)

您可以在find_by_idwhere的结果上调用update_attributes之前使用try Rails方法。

如果记录不存在,

try将静默返回nil而不会引发异常。如果记录存在,它将更新它。

found = Model.find_by_id(id).try(:update_attributes, {key: value})

答案 1 :(得分:1)

您可以将first_or_initialize与new_record结合使用吗?如下:

client = Client.where(first_name: 'Nick').first_or_initialize(locked: false)
client.save unless client.new_record?

答案 2 :(得分:0)

假设您的模型被称为“事件”并且您按ID搜索,则可以执行以下操作:

e = Event.where(:id => id)
if !e.empty?
  e.first.value = new_value
  e.first.save!
end

答案 3 :(得分:0)

在Rails 4中,这可能是我找到的最简单的解决方案:

# POST /users
# POST /users.json
def create
  @user = User.find_or_initialize_by(fbid: user_params[:fbid])
  @user.assign_attributes(user_params)
  respond_to do |format|
    if @user.save
      format.html { redirect_to @user, notice: 'User was successfully created.' }
      format.json { render action: 'show', status: :created, location: @user }
    else
      format.html { render action: 'new' }
      format.json { render json: @user.errors, status: :unprocessable_entity }
    end
  end
end

如果存在FBID的用户,则记录将被更新;否则,将创建一个新的。您可以更新记录以匹配您想要保持唯一的列。对列进行索引可能有助于搜索&检索等。

希望这有帮助!

相关问题