0

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.

2
  • Try "<%= @verbatims.to_json.html_safe %>" Commented Aug 17, 2017 at 10:58
  • thanks Pravan just tried it and I got an JS error. I tried: "<%= j @verbatims.to_json.html_safe %>" and it works to get rid of the &quot; but it still results in a string like this: "["s_1", "s_2", s_n"]" Commented Aug 17, 2017 at 11:08

1 Answer 1

2

Remove the extra quotation marks:

var verbatims = <%= raw @verbatims.to_json %>;
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks vijoc. I didn't notice the code with the raw command was meant to be without the quotes.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.