How to convert this sql into named_scope

hi, i have a sql statement which has a subquery on itself. it gets all
the unique invitees of a given event from table invitation. i came up
with the sql but i don’t know how to convert it into a named_scope
which i can reuse in other places. please help.

sql:

select * from invitations inv
join (select event_id, user_id, max(invite_time) as last_invite_time
from invitations group by event_id, user_id) as last_inv
on
inv.event_id = last_inv.event_id and
inv.user_id = last_inv.user_id and
inv.invite_time = last_inv.last_invite_time and
inv.event_id = @event_id

thanks
batterhead

Correct me if I’m wrong, but can’t that query be rewritten as follows:

select event_id, user_id, max(invite_time) as last_invite_time
from invitations
where event_id = @event_id
group by event_id, user_id

Basically you want to get distinct event_id and user_id and the latest
invite_time? No need to join to itself.

In that case, you could go ahead and do it like this in ActiveRecord:

Invitation.select(“event_id, user_id, max(invite_time) as
last_invite_time”).group(“event_id,
user_id”).where(:event_id => @event_id)

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs