1

我在下面有一个 List 模型,它与收件人有一个 has_and_belongs_to_many 关联。该方法的目的是以这种格式make_recipient_lists保存(初始参数)的解析csv 。numbers[[num1],[num2],[num3]...]

add_recipients通过查找现有收件人然后将其添加到列表或创建新收件人来工作。

整个过程在 28 分钟内适用于少量 20k 的数字。但是,数字越大,所需的时间越长,70k 需要 14 小时。可能是因为它正在检查缓存的重复项current_lists

问题是,有什么办法可以加快速度吗?我可能错误地处理了这个问题。谢谢!

class List < ActiveRecord::Base

#other methods above

  def make_recipient_lists(numbers,options)
    rejected_numbers = []
    account = self.user.account

    #caching recipients
    current_recipients = self.recipients

    numbers.each do |num|
      add_recipient(num[0], current_recipients)
    end

  end

  def add_recipient(num, current_recipients)
    account = self.user.account

    recipient = current_recipients.where(number:num, account_id: account.id).first
    recipient ||= current_recipients.create!(number:num, account_id: account.id)

    recipient
  end

end
4

2 回答 2

0

我认为,您应该使用 rails active_record 查询接口。您可以为此使用方法 find_or_create 方法:它将使您的查询更快。像这样改变你的方法,并检查时差:

def make_recipient_lists(numbers,options)
    rejected_numbers = []
    account = self.user.account

    #caching recipients
    current_recipients = self.recipients

    numbers.each do |num|
      self.recipients.find_or_create_by(number: num, account_id: account.id)      
    end
end

希望它会有所帮助。谢谢。

于 2013-07-27T07:18:06.283 回答
0

你可以做这样的事情。我没有测试过这个,但你明白了。

  def make_recipient_lists(numbers, options)
    rejected_numbers = []
    account = self.user.account
    existing_numbers = self.recipients.where(number: numbers, account_id: account.id).map(&:number)
    new_records = (numbers - existing_numbers).map {|n| {number: n, account_id: account.id, list_id: self.id} }

    Recipient.create new_records
  end
于 2013-07-27T07:11:54.020 回答