如果记录不存在则创建

gsu*_*008 20 ruby-on-rails ruby-on-rails-4

我的rails应用程序中有3个型号

class Contact < ActiveRecord::Base
  belongs_to :survey, counter_cache: :contact_count
  belongs_to :voter
  has_many :contact_attempts
end

class Survey < ActiveRecord::Base
  has_many :questions
  has_many :contacts
end

class Voter < ActiveRecord::Base
  has_many :contacts
end
Run Code Online (Sandbox Code Playgroud)

联系人包含voter_id和survey_id.我的应用程序的逻辑是,在任何给定的调查中,选民只能有一个联系人.

现在我正在使用以下代码来强制执行此逻辑.我在contacts表中查询与给定的voter_id和survey_id匹配的记录.如果不存在则创建它.否则它什么都不做.

if !Contact.exists?(:survey_id => survey, :voter_id => voter)
   c = Contact.new
   c.survey_id = survey
   c.voter_id = voter
   c.save
end
Run Code Online (Sandbox Code Playgroud)

显然,这需要select和insert查询来创建1个潜在联系人.当我一次添加可能数千个联系人时.

现在我正在使用Resque允许在后台运行并远离ui线程.我该怎么做才能加快速度,提高效率?

baz*_*012 33

您可以执行以下操作:

Contact.where(survey_id: survey,voter_id: voter).first_or_create
Run Code Online (Sandbox Code Playgroud)


Nic*_*nil 20

您应该首先添加一个数据库索引,以尽可能将此条件强制为最低级别:

add_index :contacts, [:voter_id, :survey_id], unique: true
Run Code Online (Sandbox Code Playgroud)

然后,您应该在ActiveRecord级别添加唯一性验证:

validates_uniqueness_of :voter_id, scope: [:survey_id]
Run Code Online (Sandbox Code Playgroud)

然后contact.save将返回false如果联系人存在指定的投票和调查.

更新:如果您创建索引,那么唯一性验证将运行得非常快.


cas*_*ral 11

看看这些链接是否可以帮助您.

这些链接适用于rails 4.0.2,但您可以更改api基座

从apidock:first_or_create,find_or_create_by
来自Rails指南:find-or-create-by