【问题标题】:Rails ajax get data from s3 not workingRails ajax从s3获取数据不起作用
【发布时间】:2014-02-13 18:14:10
【问题描述】:

我有一个表单域

<%= select_tag "select", options_for_select(@folders),:include_blank => true %>  

我正在做一个 ajax 调用(来自new.html.erb):

$(document).ready(function(){
    $("#select").change(function(){
        $.ajax({
          type: "PUT",
          data: {folder: $(this).val()},
          headers: {
            'X-CSRF-Token': '<%= form_authenticity_token.to_s %>'
          },
          url: "/get_files"
      });
    });
});  

get_files 操作:

def get_files
    folder=params[:folder]+"/"
    @files= #getting all the files in a folder as array
    respond_to do |format|
       format.js
    end
end  

get_files.js.erb

$("#audio").html("<%=escape_javascript(render(@files)) %>");  

new.html.erb

<div id="audio">
  <%= render @files if @files %>
</div>  

_files.html.erb

<%= f.input :select_audio, collection: @files, as: :select %>  

但我得到:

> /get_files 处的参数错误

'"content.docx"' 不是返回有效部分路径的 ActiveModel 兼容对象。

这里content.docx@files 数组的第一个文件。这里有什么问题? 我正在尝试从 AWS s3 获取文件夹的所有文件。用户选择一个文件夹,然后对 get_files 进行 ajax 调用,该调用返回一个文件夹中的文件,该文件夹是一个数组。
即使我手动将@files 实例变量设置为[1,2,3,4],我也会遇到同样的错误。

如果我设置@files="hello",它会要求hello 部分。为什么这不起作用?

【问题讨论】:

  • 你应该尝试在表单标签上使用 remote: true 选项作为 ajax 提交整个文件。
  • 我不想通过 ajax 提交整个表单。我只是想通过对 AWS S3 的 ajax 调用来更新表单字段。

标签: ruby-on-rails ajax ruby-on-rails-3 amazon-s3


【解决方案1】:

首先改变

$("#audio").html("<%=escape_javascript(render(@files)) %>");

$("#audio").html("<%=escape_javascript(render partial: 'files', locals: { files:@files } ) %>"); 

然后在你的部分中你应该写

<%= select_tag "select_audio", options_for_select(files) %>

有关选择标签的更多信息,请参阅select_tag

【讨论】:

  • 效果很好。谢谢。只需要做一个小改动。 options_from_collection_for_selectoptions_for_select 因为 files 是一个数组。
【解决方案2】:

看起来有错误:

$("#audio").html("<%=escape_javascript(render(@files)) %>");  

我认为应该是:

$("#audio").html("<%=escape_javascript(render 'files' ) %>"); 

实际上能够渲染 _files.html.erb 部分

【讨论】:

  • 感谢您解决了问题。但是现在我在课堂上得到了undefined local variable or method f'...`为什么不能在部分中访问f
  • 是的,因为新请求没有f 的上下文,您可能已经在表单中开始了。您必须修改 _files.html.erb 以改为使用 input_tag rails helper for same..
  • 你能告诉我怎么做吗?我试过:*f, files: @files} %> 但结果还是一样。
猜你喜欢
  • 1970-01-01
  • 2011-10-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-06-09
  • 2018-01-23
  • 1970-01-01
相关资源
最近更新 更多