Rails find_or_create_by 块在查找情况下运行在哪里?

发布于 2024-10-27 12:27:59 字数 273 浏览 4 评论 0原文

ActiveRecord find_or_create_by 动态查找器方法允许我指定一个块。文档对此并不清楚,但似乎该块仅在创建情况下运行,而不在查找情况下运行。换句话说,如果找到该记录,则该块不会运行。我用这个控制台代码测试了它:(

User.find_or_create_by_name("An Existing Name") do |u|
  puts "I'M IN THE BLOCK"
end

没有打印任何内容)。有没有办法让块在这两种情况下都运行?

The ActiveRecord find_or_create_by dynamic finder method allows me to specify a block. The documentation isn't clear on this, but it seems that the block only runs in the create case, and not in the find case. In other words, if the record is found, the block doesn't run. I tested it with this console code:

User.find_or_create_by_name("An Existing Name") do |u|
  puts "I'M IN THE BLOCK"
end

(nothing was printed). Is there any way to have the block run in both cases?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

桜花祭 2024-11-03 12:28:00

据我了解,如果没有找到任何内容,块将被执行。它的用例如下所示:

User.find_or_create_by_name("Pedro") do |u|
  u.money = 0
  u.country = "Mexico"
  puts "User is created"
end

如果找不到用户,它将初始化名为“Pedro”的新用户以及块内的所有这些内容,并将返回新创建的用户。如果用户存在,它将仅返回该用户而不执行该块。

您还可以使用“块样式”其他方法,例如:

User.create do |u|
  u.name = "Pedro"
  u.money = 1000
end

它的作用与 User.create( :name => "Pedro", :money => 1000 ) 相同,但看起来更好一些

User.find(19) do |u|
  ..
end

ETC

As far as I understand block will be executed if nothing found. Usecase of it looks like this:

User.find_or_create_by_name("Pedro") do |u|
  u.money = 0
  u.country = "Mexico"
  puts "User is created"
end

If user is not found the it will initialized new User with name "Pedro" and all this stuff inside block and will return new created user. If user exists it will just return this user without executing the block.

Also you can use "block style" other methods like:

User.create do |u|
  u.name = "Pedro"
  u.money = 1000
end

It will do the same as User.create( :name => "Pedro", :money => 1000 ) but looks little nicer

and

User.find(19) do |u|
  ..
end

etc

昵称有卵用 2024-11-03 12:28:00

在我看来,这个问题实际上并没有得到回答,所以我会回答。我认为这是最简单的方法,您可以实现这一目标:

User.find_or_create_by_name("An Existing Name or Non Existing Name").tap do |u|
  puts "I'M IN THE BLOCK REGARDLESS OF THE NAME'S EXISTENCE"
end

干杯!

It doesn't seem to me that this question is actually answered so I will. This is the simplest way, I think, you can achieve that:

User.find_or_create_by_name("An Existing Name or Non Existing Name").tap do |u|
  puts "I'M IN THE BLOCK REGARDLESS OF THE NAME'S EXISTENCE"
end

Cheers!

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文