0

レコードを作成してから、作成後のフィルターから、新しく作成されたレコードの ID をキューにプッシュしています。

別のスクリプトから、キューからIDを読み取り、IDのdbレコードを即座に読み取ります。

record = Model.find(id)# this is giving error: Couldn't find record with ID 8732

mysql2 gem で rails 2.3.14 を使用しています。

4

3 に答える 3

1

あなたが経験していることは、競合状態として知られています。

ilan が指摘したように、2 番目のスクリプトまたはワーカー ライブラリは、レコードが完全に書き込まれる (「コミット」される) 前にレコードにアクセスしようとしています。

この問題の一般的な解決策は、after_create / after_save などの代わりにafter_commitコールバックを使用することです。

Rails BestPractices に関する記事の例。

前:

class Notification < ActiveRecord::Base
  after_create :asyns_send_notification

  def async_send_notification
    NotificationWorker.async_send_notification({:notification_id => id})
  end
end

class NotificationWorker < Workling::Base
  def send_notification(params)
    notification = Notification.find(params[:notification_id])
    user = notification.user
    # send notification to user's friends by email
  end
end

after_commit ライフサイクル フックを使用したリファクタリング後:

class Notification < ActiveRecord::Base
  after_commit :asyns_send_notification, :on => :create

  def async_send_notification
    NotificationWorker.async_send_notification({:notification_id => id})
  end
end

詳細情報: Rails API docs の after_commit

于 2013-03-14T20:54:52.097 に答える
0

たぶん、クエリ結果"SELECT * FROM Model WHERE id=8732"はキャッシュにあります。

クエリを「リロード」してみてください。

record = Model.find_by_id(id, true)
于 2013-03-14T14:57:38.807 に答える
0

その理由は、トランザクションの分離レベルに関係しています。挿入したエントリを読み取ることはできますが、別のプロセスはトランザクションがコミットされるまで読み取れません。このコミットは、コントローラーが戻った後に発生します。

于 2013-03-14T20:16:47.493 に答える