如果记录存在,如何设置变量(How to set a variable if a record exists)

编程入门 行业动态 更新时间:2024-10-27 22:19:36
如果记录存在,如何设置变量(How to set a variable if a record exists)

在“创建”对象之前检查记录是否存在的最佳方法是什么?

@tag = Tag.find_by_name(tag) if @tag do_something else do_something_else end

你可以做:

if @tag = Tag.find_by_name(tag) do_something else do_something_else end

What is the best way to check if a record exists before 'creating' the object?

@tag = Tag.find_by_name(tag) if @tag do_something else do_something_else end

Can you do:

if @tag = Tag.find_by_name(tag) do_something else do_something_else end

最满意答案

两个版本都很好。 使用后者很常见,因为它更简洁。 但是,为了便于阅读,您可能需要使用

if (@tag = Tag.find_by_name(tag))

这不是必需的,但它使得它更明确地表明你正在做一项任务而不是比较。

if @tag == Tag.find_by_name(tag)

用括号括起来更加明确。 它说,分配,然后评估结果。

此外,如果您实际上不需要标签对象本身,并且您只关心存在,您可能想要使用exist?

if Tag.exists?(name: tag)

这样会更快,因为它使用SELECT COUNT SQL查询而不是完整的SELECT 。 它基本上不会实例化记录。

Both versions are perfectly fine. It's very common to use the latter, because it's more concise. However, for readability, you may want to use

if (@tag = Tag.find_by_name(tag))

This is not necessary, but it makes it more explicit that you are doing an assignment and not a comparison.

if @tag == Tag.find_by_name(tag)

Wrapping it into parenthesis is more explicit. It says, assign, then evaluate the result.

Furthermore, if you don't actually need the tag object itself, and you just care for the existence, you may want to use exist?

if Tag.exists?(name: tag)

This is faster, because it uses a SELECT COUNT SQL query and not a full SELECT. It basically doesn't instantiate the record.

更多推荐

本文发布于:2023-07-20 07:25:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1195952.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:变量   如何设置   set   exists   record

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!