Rails find_or_create_by 块在查找情况下运行在哪里?
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
据我了解,如果没有找到任何内容,块将被执行。它的用例如下所示:
如果找不到用户,它将初始化名为“Pedro”的新用户以及块内的所有这些内容,并将返回新创建的用户。如果用户存在,它将仅返回该用户而不执行该块。
您还可以使用“块样式”其他方法,例如:
它的作用与
User.create( :name => "Pedro", :money => 1000 )
相同,但看起来更好一些,
ETC
As far as I understand block will be executed if nothing found. Usecase of it looks like this:
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:
It will do the same as
User.create( :name => "Pedro", :money => 1000 )
but looks little nicerand
etc
在我看来,这个问题实际上并没有得到回答,所以我会回答。我认为这是最简单的方法,您可以实现这一目标:
干杯!
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:
Cheers!