mercredi 25 mai 2016

Most efficient way to find random item not present in join table and without repeating previous random item

In my Rails 4 app I have an Item model and a Flag model. Item has_many Flags. Flags belong_to Item. Flag has the attributes item_id, user_id, and reason. I am using enum for pending status. I need the most efficient way to get an item that doesn't exist in the flags table because I have a VERY large table. I also need to make sure that when a user clicks to generate another random item, it will not repeat the current random item back to back. It would be OK to repeat any time afterwards, just not back to back.

This is what I have so far:

def pending_item
  @pending_items = UserItem.joins("LEFT OUTER JOIN flags ON flags.item_id = items.id").
                   where("items.user_id != #{current_user.id} and flags.id is null")
  @pending_item = @pending_badges.offset(rand @pending_badges.count).first
end

Is there a more efficient way than this?

And how can I make sure there are no back to back repeats of the same pending_item?




Aucun commentaire:

Enregistrer un commentaire