mardi 5 juillet 2016

show different record with order('RANDOM()')

I'm trying to show a random record in my index view upon on reload, but I want that record to be different than the current one. In my Word model, words have terms, which are what I'm trying to display (i.e. with <%= @word.term %>. I've been trying to implement the answers from this post, but they're not working.

Currently, this shows random records, but will repeat the current one on occasion:

def index
  @word = Word.order("RANDOM()").first
end

If I try

def index
  @word = Word.where("id != ?", params[:id]).shuffle.first
end

I see undefined method 'term' for nil:NilClass. How can I implement the random order while avoiding a repeated record on reload?




Aucun commentaire:

Enregistrer un commentaire