微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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创建所需的查询数相比.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐