Rails first_or_create ActiveRecord方法 [英] Rails first_or_create ActiveRecord method

查看:68
本文介绍了Rails first_or_create ActiveRecord方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

first_or_create / first_or_create!方法在Rails中做什么?

What does the first_or_create / first_or_create! method do in Rails?

根据文档,方法"没有描述"...

According to the documentation, the method "has no description"...

推荐答案

来自指南

first_or_create

first_or_create 方法检查 first 是否返回nil.如果确实返回nil,则调用 create .与 where 方法结合使用时,此功能非常强大.让我们来看一个例子.

The first_or_create method checks whether first returns nil or not. If it does return nil, then create is called. This is very powerful when coupled with the where method. Let’s see an example.

假设您要查找一个名为"Andy"的客户端,如果没有,请创建一个客户端,并将其locked属性设置为false.您可以通过运行以下命令来实现:

Suppose you want to find a client named ‘Andy’, and if there’s none, create one and additionally set his locked attribute to false. You can do so by running:

Client.where(:first_name => 'Andy').first_or_create(:locked => false)
# => #<Client id: 1, first_name: "Andy", orders_count: 0, locked: false, created_at: "2011-08-30 06:09:27", updated_at: "2011-08-30 06:09:27">

此方法生成的SQL如下所示:

The SQL generated by this method looks like this:

SELECT * FROM clients WHERE (clients.first_name = 'Andy') LIMIT 1
BEGIN
INSERT INTO clients (created_at, first_name, locked, orders_count, updated_at) VALUES ('2011-08-30 05:22:57', 'Andy', 0, NULL, '2011-08-30 05:22:57')
COMMIT

first_or_create 返回已存在的记录或新记录.在我们的情况下,我们还没有名为Andy的客户,因此创建并返回了记录.

first_or_create returns either the record that already exists or the new record. In our case, we didn’t already have a client named Andy so the record is created and returned.

first_or_create!

如果新记录无效,您也可以使用 first_or_create!引发异常.验证未包含在本指南中,但让我们假设您暂时添加了

You can also use first_or_create! to raise an exception if the new record is invalid. Validations are not covered on this guide, but let’s assume for a moment that you temporarily add

validates :orders_count, :presence => true

到您的客户模型.如果您尝试在不传递orders_count的情况下创建新客户端,则该记录将无效并引发异常:

to your Client model. If you try to create a new Client without passing an orders_count, the record will be invalid and an exception will be raised:

Client.where(:first_name => 'Andy').first_or_create!(:locked => false)
# => ActiveRecord::RecordInvalid: Validation failed: Orders count can't be blank

这篇关于Rails first_or_create ActiveRecord方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆