alopez02
alopez02

Reputation: 1524

Wrong format when passing an array of strings to java script from Rails controller

I have a rather atypical set-up in one of my Rails controllers in that it can create a series of objects (instead of only a single one) depending the parameters received.

I'd like the controller to respond_to js and pass such group of objects, just created, as an array to my js.erb file.

Unfortunately, I haven't been able to pass the array to JS in the appropriate format.

A bit of pseudo code to illustrate my controller below:

Controllers/verbatims_controller.rb

 def create
  # Code here returns an array of strings 
  # Each string of the array is converted into a Verbatim instance
  # I create again an array of strings by 'plucking' the 'content' attribute (a string) from each verbatim object 
  # I set @verbatims to take the value of that array of strings as below
  @verbatims = @answer.verbatims.pluck(:content)
  # At this point I'm sure @verbatims returns an array of the form ["string_1", "string_2", "string_n"] 

  respond_to do |format|
    format.js { render 'verbatims_for_answers.js.erb'
  end
end

Views/verbatims/verbatims_for_answers.js.erb

// I set my JS variable as below
var verbatims = ("<%= j @verbatims.to_json %>");
// which returns a string like:
"[&quot;string_1&quot;,&quot;string_2&quot;,&quot;string_n&quot;]"

I have tried using raw as suggested in a post in StackOverflow without success like:

var verbatims = ("<%= raw @verbatims.to_json %>");

Or converting to json from the controller but still no luck.

Hope you can help.

Upvotes: 0

Views: 200

Answers (1)

vijoc
vijoc

Reputation: 693

Remove the extra quotation marks:

var verbatims = <%= raw @verbatims.to_json %>;

Upvotes: 2

Related Questions