got*_*tqn 7 ruby ajax controller ruby-on-rails-3 simple-form
我正在使用simple_form gem并生成我正在指定remote:true选项的表单,如下所示:
<%= simple_form_for @webinar, validate: true, remote:true do |f| %>
Run Code Online (Sandbox Code Playgroud)
因此,表单的输出html是以下片段:
<form accept-charset="UTF-8" action="/webinars" class="simple_form new_webinar" data-remote="true" data-validate="true" enctype="multipart/form-data" id="new_webinar" method="post" novalidate="novalidate"> ... </form>
Run Code Online (Sandbox Code Playgroud)
在我检查时,使用标准的form_for帮助器是在使用remote:true选项时将data-remote ='true'添加到表单中.正如你从生成的html中看到的那样,当我使用simple_form gem时,也有这样的属性.
所以,在我的控制器中,我有:
def create
@webinar = Webinar.new(params[:webinar])
respond_to do |format|
if @webinar.save
format.html { redirect_to @webinar, notice: 'Webinar was successfully created.' }
format.js
format.json { render json: @webinar, status: :created, location: @webinar }
else
format.html { render action: "new" }
format.json { render json: @webinar.errors, status: :unprocessable_entity }
end
end
end
Run Code Online (Sandbox Code Playgroud)
但是,始终使用format.html.我做错了什么?
编辑:
我已经使用logger.debug request.format来检查请求的实际格式是什么,在日志文件中它是:
text/html的
所以,问题必须是simple_form生成的形式 - 当我们有"data-remote = true"时会出现什么问题?
我不敢相信我花了这么多时间试图理解为什么 simple_form没有按预期工作。
最后,看来我已经以正确的方式完成了所有事情,导致问题的原因是:
AJAX 不能用于文件上传。
为了解决我的问题,我只需将以下 gem 添加到我的Gemfile中并运行捆绑安装命令:
gem 'remotipart', '~> 1.0'
Run Code Online (Sandbox Code Playgroud)
然后在我的application.js文件中添加以下行:
//= 需要 jquery.remotipart
有关以下内容的更多信息: