Ajax 使用路由检查数据库更改

Ajax check for database change using route

我正在使用带有 Delayed::Job 的 Paperclip 在后台处理照片。处理完成后,模型应将 photo.attachment_is_processing 设置为 false。

我需要在客户端检查此更改。我知道我可以通过使用 Ajax 查询路线来做到这一点,但是:

路线应该是什么样的?

来自schema.rb的可能线索:

  create_table "forem_posts", force: :cascade do |t|
    t.integer  "topic_id"
    t.text     "text"
    t.integer  "user_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.integer  "reply_to_id"
    t.string   "state",       default: "pending_review"
    t.boolean  "notified",    default: false
  end

  create_table "photos", force: :cascade do |t|
    t.integer  "post_id"
    t.datetime "created_at"
    t.datetime "updated_at"
    t.string   "attachment_file_name"
    t.string   "attachment_content_type"
    t.integer  "attachment_file_size"
    t.datetime "attachment_updated_at"
    t.boolean  "attachment_is_animated"
    t.boolean  "attachment_is_processing", default: false
  end

来自 rake routes 的可能线索:

            forum_topic_posts POST   /:forum_id/topics/:topic_id/posts(.:format)              forem/posts#create
         new_forum_topic_post GET    /:forum_id/topics/:topic_id/posts/new(.:format)          forem/posts#new
        edit_forum_topic_post GET    /:forum_id/topics/:topic_id/posts/:id/edit(.:format)     forem/posts#edit
             forum_topic_post GET    /:forum_id/topics/:topic_id/posts/:id(.:format)          forem/posts#show
                              PATCH  /:forum_id/topics/:topic_id/posts/:id(.:format)          forem/posts#update
                              PUT    /:forum_id/topics/:topic_id/posts/:id(.:format)          forem/posts#update

完成后,我如何实际将 photo.attachment_is_processing 与从该路由返回的 true 或 false 联系起来?

你可能想要这样的东西:

routes.rb

get '/check_photo_processing/:id', to: 'photos#check_photo_processing', as: :check_photo_processing

photos_controller.rb

def check_photo_processing
  @photo_status = Photo.find(params[:photo_id]).attachment_is_processing
  respond_to do |wants|
    wants.js
  end
end

然后在views/photos/check_photo_processing.js

alert("<%= @photo_status %>");
// do what you gotta do with the status here

最后,为了将它们联系在一起,您需要一个函数来创建 AJAX 请求。如果您在应用中使用 Coffeescript:

check_photo_status: ( photo_id ) ->
    $.ajax(
        type: 'GET'
        url: "/check_photo_status/#{ photo_id }.js"
    )

然后从某处的视图中调用它

<script>
  check_photo_status(@photo.id);
  // or pass in the photo id somehow
</script>

因为问题中没有提供太多的示例代码,所以这只是一个基本的配置,如何完成你所需要的。您可能需要稍微调整一下才能使其与您的应用程序一起使用。