在application.js中使用嵌入式ruby

时间:2015-02-05 10:06:34

标签: javascript ruby-on-rails heroku

我正在关注Heroku图片上传tutorial,其中包含application.js中的以下代码 -

fileInput.fileupload({
      fileInput:       fileInput,
      url:             '<%= @s3_direct_post.url %>',
      type:            'POST',
      autoUpload:       true,
      formData:         <%= @s3_direct_post.fields.to_json.html_safe %>,
      paramName:        'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
      dataType:         'XML',  // S3 returns XML if success_action_status is set to 201
      replaceFileInput: false
    });

...您可以看到formData:在erb周围没有引号 - 这在我部署代码时导致javascript错误 - SyntaxError: Unexpected token '<'

那个erb应该用引号,对吗?任何评论都非常感谢。

1 个答案:

答案 0 :(得分:1)

不要这样做 - 它可能在开发中起作用,但是由于默认生产配置假设所有资产都是预编译的并且由服务器提供服务,因此它将在生产中中断。这显然可以改变,但可能会导致一些性能问题。

如果您需要将控制器中的任何数据传递给javascript,请使用gon gem:

控制器:

gon.fileUpload = {
  url: @s3_direct_post.url,
  data: @s3_direct_post.fields.to_json
}

然后你可以在100%静态javascript中使用它:

fileInput.fileupload({
      fileInput:       fileInput,
      url:             gon.fileUpload.url
      type:            'POST',
      autoUpload:       true,
      formData:         gon.fileUpload.data,
      paramName:        'file', // S3 does not like nested name fields i.e. name="user[avatar_url]"
      dataType:         'XML',  // S3 returns XML if success_action_status is set to 201
      replaceFileInput: false
    });

当然,您需要遵循gon安装指南。