ruby-on-rails – 更高效在Rails中查找或创建多个记录
发布时间:2020-12-17 02:52:01 所属栏目:百科 来源:网络整理
导读:我有一个应用程序需要发送用户事件邀请.当用户邀请朋友(用户)参加活动时,如果尚不存在将用户连接到该事件的新记录,则创建该记录.我的模型由user,event和events_user组成. class Event def invite(user_id,*args) user_id.each do |u| e = EventsUser.find_or
我有一个应用程序需要发送用户事件邀请.当用户邀请朋友(用户)参加活动时,如果尚不存在将用户连接到该事件的新记录,则创建该记录.我的模型由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创建所需的查询数相比. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
推荐文章
站长推荐
热点阅读