簡體   English   中英

Rails:如何在每個用戶獨有的Rails中生成隨機的“下一個帖子”順序?

[英]Rails: How to generate a random order of “next post” in rails unique to each user?

我有一個模型,用戶可以在其中輸入選擇題。 我有一個視圖,用戶可以單擊“上一個”或“下一個”,並且在數據庫中將它們占用1或1。

但是,我想這樣做。

答:用戶單擊“下一個”,將轉到一個以前從未查看過的新隨機問題

B.用戶單擊“上一個”,進入完成的最后一個問題 ,以及在此之前完成的最后一個問題。

C.與其他用戶相比,用戶的“下一個”順序應不同。

我該怎么做呢?

post.rb

def next
    Post.where("id > ?", id).order(id: :asc).limit(1).first
end

def prev
     Post.where("id < ?", id).order(id: :desc).limit(1).first
end

posts_controller.rb

def show 
@post = Post.friendly.find(params[:id])


# this is used in the show.html.erb view for posts
@randomize_posts = [
  @post.answer_choice,
  @post.answer_choice_2,
  @post.answer_choice_3,
  @post.answer_choice_4,
  @post.answer_choice_5
].shuffle

end

posts / show.html.erb

<%= link_to "← Previous Question", @post.prev, :class => 'button previous-question' %>

<%= link_to "Next Question →", @post.next, :class => 'button next-question' %>

有幾種方法可以做到這一點。 我建議您采用確定性方法,讓不同的用戶獲得不同的結果,但同一用戶將始終具有相同的結果。 這使您具有隨機性,並且可以進行前/后導航而無需存儲額外的數據。

要以確定性方式隨機化,可以在帖子的ID和當前用戶ID上應用md5方法:

posts = Post.order("md5('#{current_user.id}' || posts.id::text)")

現在,查找下一個和上一個的最簡單方法是查看哪個在當前的之后和之前。 您可以通過計算其md5哈希值來了解當前位置,因此您只需要查找哪個位置md5其后:

Post
  .where("md5('?' || '?') > md5('?' || posts.id::text)", current_user.id, id, current_user.id)
  .order("md5('#{current_user.id}' || posts.id::text)")
  .limit(1)

將其應用於您的模型,它可能類似於:

def next(user)
   ordered_posts(user)
     .where("md5('?' || '?') > md5('?' || posts.id::text)", user.id, id, user.id)
end

def prev(user)
  ordered_posts(user)
     .where("md5('?' || '?') < md5('?' || posts.id::text)", user.id, id, user.id)
end

private

def ordered_posts(user)
  Post.order("md5('#{current_user.id}' || posts.id::text)")
end

而且視圖看起來像:

<%= link_to "← Previous Question", @post.prev(current_user), :class => 'button previous-question' %>

<%= link_to "Next Question →", @post.next(current_user), :class => 'button next-question' %>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM