0

この比較的 nu-b の質問をご覧いただきありがとうございます。

Rails 3 で構築された Web アプリを使用して、ユーザーが一度に複数のストーリーを表示できるようにし、各ストーリーには複数の投稿があります。JS を使用して定期的にサーバーをポーリングし、開いているすべてのストーリーで新しい投稿を検索します。サーバーをポーリングするたびに投稿のテーブル全体を最初から検索する必要がないように、セッション変数を使用して、開いている各ストーリーの最後の検索をどこで終了したかを追跡します。

ユーザーが最初にストーリーを開いたときのアクションは次のとおりです。

def open_story
    story = Story.find(params[:story_id])
    #keep track of the last post searched for each open story so to assist when we poll for new posts to that story
    last_post_searched = Post.last.id
    session["last_post_searched_for_story_#{story.id}"] = last_post_searched 
    @posts = story.posts.where("posts.id <= ?", last_post_searched)
    respond_with @posts
end

以下は、クライアントが一連のオープン ストーリーの新しい投稿の更新をサーバーにポーリングするときのアクションです。

  def update_stories
    open_stories_id_array = params[:open_stories]
    open_stories_id_array.each { |open_story_id|
debugger
      start_search_at_post_id = session["last_post_searched_for_story_#{open_story_id}"] + 1
      session["last_post_searched_for_story_#{open_story_id}"] = Post.last.id
      story = Story.find(open_story_id)
      updates = story.posts.where("posts.id between ? AND ?", 
          start_search_at_post_id, session["last_post_searched_for_story_#{open_story_id}"])
      results[open_story_id] = updates
    }
    respond_with(results)
  end

理由がわかりませんが、update_stories アクションでセッション変数が新しい Post.last.id にタイムリーにインクリメントされません。問題を再現する方法は次のとおりです。

  1. データベースにさまざまなストーリーへの 30 の投稿があるとします。
  2. ストーリー 1 で open_story を呼び出します。これにより、session["last_post_searched_for_story_1"] が 30 に設定されます。
  3. 次に、ストーリー 1 (投稿 31) に新しい投稿を作成します。
  4. 私のクライアントは update_stories アクションをポーリングして、ストーリー 1 の新しい投稿を取得します。
  5. update_stories は、ID が 1 のストーリーの ID が 31 から 31 の投稿を検索し、作成したばかりの投稿を返します。
  6. その後、しばらくして、クライアントは update_stories を再度自動的にポーリングし、ストーリー 1 の新しい投稿がないかどうかを確認します。ここで問題が発生します。

値 31 を含む session["last_post_searched_for_story_1"] の代わりに、以前の値 30 を保持するため、データベース検索で元の新しい投稿が 2 回目に返されます。多くの場合、クライアントは、session["last_post_searched_for_story_1"] が 31 にインクリメントされる前に update_stories を数回呼び出します。セッション変数が新しい値を保存するのが非常に遅いか、何らかの遅延読み込みの問題が発生しているかのようです。

この問題を解決するための助けは大歓迎であり、熱心に受け入れられます。

ありがとう

ところで、まだ学ぶべきことがたくさんあるので、この問題を処理するためのより良い方法について、または Rails のベスト プラクティスに違反している場合は、遠慮なくフィードバックをお寄せください。

4

1 に答える 1

-1

あなたのコードには 2 つの問題があります。

最後の方法を適用する前に、最初に結果を並べ替えることができます。データベースから返された最後のレコードが、必ずしも最後に作成されるとは限りません。
次に、最後の投稿を選択するには、その記事の投稿のみに最後の基準を適用してから、その記事の最後の投稿を選択する必要があります。
したがって、これの代わりに:

story = Story.find(params[:story_id])
#keep track of the last post searched for each open story so to assist when we poll for new posts to that story
last_post_searched = Post.last.id

次のようにすることができます。

story = Story.find(params[:story_id])
last_post_searched = Post.joins(:stories).where("stories.id = ?", story.id).order("posts.created_on DESC").first  
于 2012-05-23T23:38:53.493 に答える