Rails:检查数据库中是否存在记录的最佳方法是什么?

krn*_*krn 3 activerecord ruby-on-rails

我的方法将国家/地区列表(代码,名称)加载到数据库中,但在此之前,如果国家/地区数据尚不存在,则必须检查.这很好用:

 def self.load_countries
    get_countries.each do |country|
      code, name = country
      if find_by_code(code).nil?
        create({ 'name' => name, 'code' => code })
      end
    end
  end
Run Code Online (Sandbox Code Playgroud)

但是,由于我是Ruby新手,我想学习最佳实践.所以,在这段代码中,我不确定可能(或可能不会)优化的两件事:

  1. find_by_attribute返回"select*from table"语句.在这种情况下,当我不需要来自数据库的任何数据时 - 我只想知道记录是否存在 - 选择整行对我来说似乎有点低效.有没有更好的方法来解决这个问题?例如,使用ActiveRecord"从表中选择1 ..."
  2. 这个问题可能很愚蠢,但我想确定:当我使用get_countries.each启动循环时,是否可以使用方法而不是变量?是不是每个循环调用相同的方法(N次)?换句话说,这会更有效率:

    countries = get_countries

    countries.each do | country |

对这几行代码的任何评论都是受欢迎的,因为它的工作原理并不一定意味着我正在以正确的方式进行.

谢谢.

小智 10

你可以使用存在吗?ActiveRecord中的函数.

def self.load_countries
  get_countries.each do |country|
    code, name = country
    unless exists?(:code => code)
      create({ :name => name, :code => code })
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

get_countries函数只被调用一次.它返回一个可枚举的数据类型,然后每个数据类型遍历它们.