在“创建”对象之前检查记录是否存在的最佳方法是什么?
@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 endWhat 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 endCan 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.
更多推荐
发布评论