I have an application that should send user invitations for events. When a user invites a friend (user) to an event, a new record connecting the user to the event is created if it does not already exist. My models consist of user, event and event_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
Using
Event.first.invite([1,2,3])
I do not think this is the most efficient way to accomplish my task. I foresaw a method like
Model.find_or_create_all_by_event_id_and_user_id
but does not exist.
Models without checks
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
source
share