Ajax使用route检查数据库更改

时间:2015-03-29 13:21:55

标签: ruby-on-rails routes

我正在使用Paperclip with Delayed :: Job在后台处理照片。处理完成后,模型应将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绑定?

1 个答案:

答案 0 :(得分:1)

你可能想要这样的东西:

的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>

由于问题中没有提供大量示例代码,因此这只是如何完成所需内容的基本配置。您可能需要稍微调整一下才能使其与您的应用一起使用。