我现在花了一个星期的时间试图让这个工作起来,尽可能多地阅读有关遥控器的信息,并尝试将其设置正确,但我已经悲惨地失败了。我的表单有标题,描述,音频文件和图像文件。如果我提交没有remote: true
的表单,它可以很好地工作,但是一旦我尝试使用ajax上传表单,似乎文件没有被上传。
由于我将音频文件作为发布的要求,因此我被重定向到新操作,显示错误,指示音频'不能空白。
即使我从模型中删除了此验证,一旦我尝试上传,就没有上传音频文件。
此外,通过检查开发人员工具,我意识到我得到的回复不是javascript,而是html。
我已经尝试了其他宝石,例如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 %>
最后,我还在学习铁轨,它的arquitechture和“轨道”方式。即使我一直在尝试正确地做所有事情,但我很确定我已经即兴创作了一些部分,试图解决错误。如果你发现任何奇怪的东西并且想要分享,我会完全乐于学习好方法。如果您需要检查我的代码的任何其他部分,请告诉我。 谢谢!
答案 0 :(得分:1)
使用remotipart时,您必须在form_for中指定操作,例如 - 这应该是
<%= form_for(post, remote: true, format: "js", html: {multipart: true}, authenticity_token: true) do |f| %>
如果这适合您,请告诉我!另外,我不确定authenticity_token是否适用于此处。您可能必须进入控制器以使用before_action禁用此功能。