我有一个应用程序需要发送用户事件邀请.当用户邀请朋友(用户)参加活动时,如果尚不存在将用户连接到该事件的新记录,则创建该记录.我的模型由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创建所需的查询数相比.