ruby-on-rails – 更高效在Rails中查找或创建多个记录

我有一个应用程序需要发送用户事件邀请.当用户邀请朋友(用户)参加活动时,如果尚不存在将用户连接到该事件的新记录,则创建该记录.我的模型由user,event和events_user组成.

class Event
    def invite(user_id,*args)
        user_id.each do |u|
            e = EventsUser.find_or_create_by_event_id_and_user_id(self.id,u)
            e.save!
        end
    end
end

用法

Event.first.invite([1,2,3])

我不认为以上是完成任务的最有效方法.我设想了一种类似的方法

Model.find_or_create_all_by_event_id_and_user_id

但是一个不存在.

没有验证的模型

class User 
  has_many :events_users 
  has_many :events 
end 
class EventsUser 
  belongs_to :events 
  belongs_to :users 
end 
class Event 
  has_many :events_users 
  has_many :users,:through => :events_users 
end

解决方法

首先获取所有现有记录然后创建所有缺失记录可能会更快:

class Event
  def invite(user_ids,*args)
    existing_user_ids = event_users.where(user_id: user_ids).map(&:user_id)
    (user_ids - existing_user_ids).each do |u|
      event_users.create(user_id: u)
     end
  end
end

这样,如果所有event_users都已存在,则只进行1次查询.但是,如果不存在event_users,则此方法会执行额外查询 – 与每个EventUser创建所需的查询数相比.

相关文章

validates:conclusion,:presence=>true,:inclusion=>{...
一、redis集群搭建redis3.0以前,提供了Sentinel工具来监控各...
分享一下我老师大神的人工智能教程。零基础!通俗易懂!风趣...
上一篇博文 ruby传参之引用类型 里边定义了一个方法名 mo...
一编程与编程语言 什么是编程语言? 能够被计算机所识别的表...
Ruby类和对象Ruby是一种完美的面向对象编程语言。面向对象编...