【发布时间】:2017-04-25 14:04:48
【问题描述】:
我现在已经花了一个星期的时间试图让它发挥作用,尽可能多地阅读有关 remotipart 的内容,并尝试将其设置正确,但我失败了。我的表格有标题、描述、音频文件和图像文件。如果我在没有remote: true 的情况下提交表单,它会完美运行,但是一旦我尝试使用 ajax 上传表单,似乎文件没有被上传。
由于我将音频文件作为发布的要求,我被重定向到新操作,显示错误指示“音频”不能为空。
即使我从模型中删除此验证,一旦我尝试上传,也不会上传任何音频文件。
另外,通过检查开发人员工具,我意识到我得到的响应不是 javascript,而是 html。
我已经尝试过其他 gem,例如 jquery-uploadfile-rails,但由于不同的原因,它们都不适合我。我现在不知道该怎么办。
_form.html.erb
<%= form_for(post, html: {multipart: true, remote: true}, authenticity_token: true) do |f| %>
<div id="form-content">
<div class="input-group field">
<span class="input-group-addon"><%= f.label 'Title' %></span>
<%= f.text_field :title, class: "form-control", placeholder: "Title" %>
</div>
<div class="input-group field">
<span class="input-group-addon"><%= f.label :descrption %></span>
<%= f.text_field :description, class: "form-control", placeholder: "Brief Description" %>
</div>
<div class="input-group field">
<span class="input-group-addon"><%= f.label :audio %></span>
<%= f.file_field :audio, class: "filestyle", 'data-iconName' => "glyphicon glyphicon-music", 'data-buttonText' => "Browse" %>
</div>
<div class="input-group field">
<span class="input-group-addon"><%= f.label :art %></span>
<%= f.file_field :art, class: "filestyle", 'data-iconName' => "glyphicon glyphicon-picture", 'data-buttonText' => "Browse" %>
</div>
<%= button_tag(type: 'submit', class: "btn btn-block btn-primary", id: "btn-post") do %>
<span class="icon-ok icon-white"></span> Post now!
<% end %>
</div>
<% end %>
posts_controller.rb
def create
@post = Post.new(post_params)
@post.user_id = current_user.id
respond_to do |format|
if @post.save
format.html { redirect_to action: 'index' }
format.js
format.json { render :show, status: :created, location: @post }
else
format.html { render :new }
format.js
format.json { render json: @post.errors, status: :unprocessable_entity }
end
end
end
create.js.erb
// Display a Javascript alert
alert('success!');
<% if remotipart_submitted? %>
alert('submitted via remotipart')
<% else %>
alert('submitted via native jquery-ujs')
<% end %>
最后,我还在学习 Rails,它是架构和“rails 方式”。尽管我一直在尝试正确地做所有事情,但我很确定我一直在即兴创作一些部分,试图解决错误。如果您发现任何奇怪的东西并想分享,我将完全开放学习好方法。如果您需要检查我的代码的任何其他部分,请告诉我。 谢谢!
【问题讨论】:
标签: jquery ruby-on-rails ajax file-upload remotipart