dan
dan

Reputation: 1080

Using embedded ruby in application.js

I'm following the Heroku image upload tutorial which includes the following code in 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
    });

...you can see that formData: does not have quotes around the erb - this is causing a javascript error when I deploy the code - SyntaxError: Unexpected token '<'

That erb should be in quotes, right? Any comment greatly appreciated.

Upvotes: 0

Views: 66

Answers (1)

BroiSatse
BroiSatse

Reputation: 44725

Don't do that - it might work in development, but will break in production as default production configuration assumes all the assets are precompiled and are served by the server. This obviously can be changed, but might cause some performance issues.

If you need to pass any data from your controller to your javascript, use gon gem:

controller:

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

Then you can use it within 100% static 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
    });

Naturally you need to follow gon installation guide.

Upvotes: 1

Related Questions