我是rails的新手,当我尝试使用carrierwave通过Ajax上传文件时遇到了一些困难。以下是编码:
composition.rb
class Composition < ApplicationRecord
belongs_to :question_paper
mount_uploader :image_path, ImageUploader
validates :question_title, presence: true
validates :topic, presence: true
validates :image_path, presence: true
end
question_paper_generations_controller.rb
def composition
@composition = Composition.new
respond_to do |format|
format.js
end
end
def composition_create
@teacher = current_teacher
@question_paper = @teacher.question_papers
comp_prms = composition_params
if comp_prms[:guided] == "Guided"
comp_prms[:guided] = true
else
comp_prms[:guided] = false
end
comp_prms[:lvl_of_difficulty] = params[:composition][:lvl_of_difficulty][0].to_i
@composition = @question_paper.last.compositions.new(comp_prms)
respond_to do |format|
if @composition.save
if params[:composition][:guided] == "Guided"
format.js { render :action => "comp_guided" }
elsif params[:composition][:guided] == "Not Guided"
format.js { render :action => "comp_not_guided" }
end
else
render 'composition'
end
end
end
composition.html.erb
<%= form_for(@composition, url: composition_path, remote: true) do |f| %>
<%= render 'shared/composition_error_messages' %>
<%= f.label :question_title %>
<%= f.text_field :question_title, class: 'form-control' %>
<%= f.label :guided %>
<%= f.select :guided, options_for_select([['Guided'], ['Not Guided']]), {}, { class: 'form-control'} %>
<%= f.label :topic %>
<%= f.text_field :topic, class: 'form-control' %>
<%= f.label :level_of_difficulty %>
<%= f.select :lvl_of_difficulty, options_for_select([['1 - Easy'], ['2 - Moderate'], ['3 - Hard']]), {}, { class: 'form-control'} %>
<%= f.label :composition_image %>
<%= f.file_field :image_path, class: 'form-control' %>
<%= f.submit "Save and Continue", class: "btn btn-primary", :remote => true %>
<% end %>
首先,当我尝试提交表单时,我收到406错误。我修复了在表单中添加hidden_tag <%= hidden_field_tag :authenticity_token, form_authenticity_token %>
以包含真实性令牌。表单已成功提交,但它是以HTML而不是JS发送的,这不是我想要的,因为我需要通过Ajax提交它并在表单提交后执行一些javascript。
在添加<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
rails server log
Started POST "/composition" for 127.0.0.1 at 2018-03-12 09:34:38 +0800
Processing by QuestionPaperGenerationsController#composition_create as HTML
Parameters: {"utf8"=>"✓", "composition"=>{"question_title"=>"你好",
"guided"=>"Guided", "topic"=>"你好", "lvl_of_difficulty"=>"1 - Easy",
"image_path"=>#<ActionDispatch::Http::UploadedFile:0xc509850 @tempfile=#
<Tempfile:C:/Users/weiki/AppData/Local/Temp/RackMultipart20180312-4592-
19d63mw.jpg>, @original_filename="bg.jpg", @content_type="image/jpeg",
@headers="Content-Disposition: form-data; name=\"composition[image_path]\";
filename=\"bg.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Save and
Continue"}
Can't verify CSRF token authenticity.
Completed 422 Unprocessable Entity in 2ms (ActiveRecord: 0.0ms)
ActionController::InvalidAuthenticityToken
(ActionController::InvalidAuthenticityToken):
actionpack (5.1.2)
lib/action_controller/metal/request_forgery_protection.rb:195:in
`handle_unverified_request'
actionpack (5.1.2)
lib/action_controller/metal/request_forgery_protection.rb:227:in
`handle_unverified_request'
actionpack (5.1.2)
lib/action_controller/metal/request_forgery_protection.rb:222:in
`verify_authenticity_token'
activesupport (5.1.2) lib/active_support/callbacks.rb:413:in `block in
make_lambda'
activesupport (5.1.2) lib/active_support/callbacks.rb:197:in `block (2
levels) in halting'
actionpack (5.1.2) lib/abstract_controller/callbacks.rb:12:in `block (2
levels) in <module:Callbacks>'
activesupport (5.1.2) lib/active_support/callbacks.rb:198:in `block in
halting'
activesupport (5.1.2) lib/active_support/callbacks.rb:507:in `block in
invoke_before'
activesupport (5.1.2) lib/active_support/callbacks.rb:507:in `each'
activesupport (5.1.2) lib/active_support/callbacks.rb:507:in `invoke_before'
activesupport (5.1.2) lib/active_support/callbacks.rb:130:in `run_callbacks'
actionpack (5.1.2) lib/abstract_controller/callbacks.rb:19:in
`process_action'
actionpack (5.1.2) lib/action_controller/metal/rescue.rb:20:in
`process_action'
actionpack (5.1.2) lib/action_controller/metal/instrumentation.rb:32:in
`block in process_action'
activesupport (5.1.2) lib/active_support/notifications.rb:166:in `block in
instrument'
activesupport (5.1.2) lib/active_support/notifications/instrumenter.rb:21:in
`instrument'
activesupport (5.1.2) lib/active_support/notifications.rb:166:in
`instrument'
actionpack (5.1.2) lib/action_controller/metal/instrumentation.rb:30:in
`process_action'
actionpack (5.1.2) lib/action_controller/metal/params_wrapper.rb:252:in
`process_action'
activerecord (5.1.2) lib/active_record/railties/controller_runtime.rb:22:in
`process_action'
actionpack (5.1.2) lib/abstract_controller/base.rb:124:in `process'
actionview (5.1.2) lib/action_view/rendering.rb:30:in `process'
actionpack (5.1.2) lib/action_controller/metal.rb:189:in `dispatch'
actionpack (5.1.2) lib/action_controller/metal.rb:253:in `dispatch'
actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:49:in `dispatch'
actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:31:in `serve'
actionpack (5.1.2) lib/action_dispatch/journey/router.rb:46:in `block in
serve'
actionpack (5.1.2) lib/action_dispatch/journey/router.rb:33:in `each'
actionpack (5.1.2) lib/action_dispatch/journey/router.rb:33:in `serve'
actionpack (5.1.2) lib/action_dispatch/routing/route_set.rb:832:in `call'
remotipart (1.3.1) lib/remotipart/middleware.rb:32:in `call'
rack (2.0.3) lib/rack/etag.rb:25:in `call'
rack (2.0.3) lib/rack/conditional_get.rb:38:in `call'
rack (2.0.3) lib/rack/head.rb:12:in `call'
rack (2.0.3) lib/rack/session/abstract/id.rb:232:in `context'
rack (2.0.3) lib/rack/session/abstract/id.rb:226:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/cookies.rb:613:in `call'
activerecord (5.1.2) lib/active_record/migration.rb:556:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/callbacks.rb:26:in `block
in call'
activesupport (5.1.2) lib/active_support/callbacks.rb:97:in `run_callbacks'
actionpack (5.1.2) lib/action_dispatch/middleware/callbacks.rb:24:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/debug_exceptions.rb:59:in
`call'
web-console (3.5.1) lib/web_console/middleware.rb:135:in `call_app'
web-console (3.5.1) lib/web_console/middleware.rb:28:in `block in call'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `catch'
web-console (3.5.1) lib/web_console/middleware.rb:18:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/show_exceptions.rb:31:in
`call'
railties (5.1.2) lib/rails/rack/logger.rb:36:in `call_app'
railties (5.1.2) lib/rails/rack/logger.rb:24:in `block in call'
activesupport (5.1.2) lib/active_support/tagged_logging.rb:69:in `block in
tagged'
activesupport (5.1.2) lib/active_support/tagged_logging.rb:26:in `tagged'
activesupport (5.1.2) lib/active_support/tagged_logging.rb:69:in `tagged'
railties (5.1.2) lib/rails/rack/logger.rb:24:in `call'
sprockets-rails (3.2.1) lib/sprockets/rails/quiet_assets.rb:13:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/remote_ip.rb:79:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/request_id.rb:25:in `call'
rack (2.0.3) lib/rack/method_override.rb:22:in `call'
rack (2.0.3) lib/rack/runtime.rb:22:in `call'
activesupport (5.1.2)
lib/active_support/cache/strategy/local_cache_middleware.rb:27:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/executor.rb:12:in `call'
actionpack (5.1.2) lib/action_dispatch/middleware/static.rb:125:in `call'
rack (2.0.3) lib/rack/sendfile.rb:111:in `call'
railties (5.1.2) lib/rails/engine.rb:522:in `call'
puma (3.9.1) lib/puma/configuration.rb:224:in `call'
puma (3.9.1) lib/puma/server.rb:602:in `handle_request'
puma (3.9.1) lib/puma/server.rb:435:in `process_client'
puma (3.9.1) lib/puma/server.rb:299:in `block in run'
puma (3.9.1) lib/puma/thread_pool.rb:120:in `block in spawn_thread'
添加<%= hidden_field_tag :authenticity_token, form_authenticity_token %>
rails server log
Started POST "/composition" for 127.0.0.1 at 2018-03-12 09:42:30 +0800
Processing by QuestionPaperGenerationsController#composition_create as HTML
Parameters: {"utf8"=>"✓", "authenticity_token"=>"u+xjkaGZ3KQ4WRxYfbhsV7+tPsuhtaKDmLvo1ToLG5+DUgHbeWqtsgsy9ogJRQGinXTAYQQ2ge1CKViyJFPtAg==", "composition"=>{"question_title"=>"你好", "guided"=>"Guided", "topic"=>"你好", "lvl_of_difficulty"=>"1 - Easy", "image_path"=>#<ActionDispatch::Http::UploadedFile:0xdf30b18 @tempfile=#<Tempfile:C:/Users/weiki/AppData/Local/Temp/RackMultipart20180312-4592-fio4v3.jpg>, @original_filename="72030c760581fc40475a604dbb55bbb7.jpg", @content_type="image/jpeg", @headers="Content-Disposition: form-data; name=\"composition[image_path]\"; filename=\"72030c760581fc40475a604dbb55bbb7.jpg\"\r\nContent-Type: image/jpeg\r\n">}, "commit"=>"Save and Continue"}
Teacher Load (1.0ms) SELECT "teachers".* FROM "teachers" WHERE "teachers"."id" = ? LIMIT ? [["id", 1], ["LIMIT", 1]]
QuestionPaper Load (0.0ms) SELECT "question_papers".* FROM "question_papers" INNER JOIN "question_papers_teachers" ON "question_papers"."id" = "question_papers_teachers"."question_paper_id" WHERE "question_papers_teachers"."teacher_id" = ? ORDER BY "question_papers"."id" DESC LIMIT ? [["teacher_id", 1], ["LIMIT", 1]]
(0.0ms) begin transaction
SQL (3.0ms) INSERT INTO "compositions" ("question_title", "image_path", "guided", "lvl_of_difficulty", "topic", "question_paper_id", "created_at", "updated_at") VALUES (?, ?, ?, ?, ?, ?, ?, ?) [["question_title", "你好"], ["image_path", "72030c760581fc40475a604dbb55bbb7.jpg"], ["guided", "t"], ["lvl_of_difficulty", 1], ["topic", "你好"], ["question_paper_id", 1], ["created_at", "2018-03-12 01:42:30.578211"], ["updated_at", "2018-03-12 01:42:30.578211"]]
(142.8ms) commit transaction
Completed 406 Not Acceptable in 268ms (ActiveRecord: 147.8ms)
ActionController::UnknownFormat (ActionController::UnknownFormat):
app/controllers/question_paper_generations_controller.rb:64:in `composition_create'
经过几轮调试后,我发现它在HTML中没有响应而不是JS,我不想要。然后,我发现了一个gem-remotipart,我没有添加hidden_tag,表单可以通过Ajax提交,但它不适用于Rails 5.1。那么,关于我该怎么办呢?
答案 0 :(得分:1)
经过几轮研究,我发现我错误地配置了remotipart,并设法通过Ajax对file_field进行表单提交。