1

I am using rails code to populate some html and JS code into mysql DB. The code is then fetched from DB and rendered on a configurable page. In the HAML file, When I use ruby code in a JS alert it works fine:

alert("#{user.id}")

the id is displayed because I pass the user object to this page. Now when I save this line alert("#{user.id}") in DB and render the JS code, it alerts #{user.id} as a string. How do I make it realize that the string coming from DB is not just a string, it is some ruby code which needs to be interpreted on the page as I am getting the user object there. So it should display the actual id like 5 or 6 instead of showing a simple string "#{user.id}"

Plz help

0

3 Answers 3

1

If it is okay to change the syntax (something like alert("<%= user.id %>")), you can use ERB or some other similar templating engine.

Here's how to do it with ERB.

require 'erb'
user_id = 23
str = 'alert("<%= user_id %>")' # get these from the database
ERB.new(str).result(binding)

Note that this is dangerous because it means that users can actually run code from within the ERB.

To get around this I suggest using another templating language.

Here are some options:

Sign up to request clarification or add additional context in comments.

2 Comments

thanks for the answer. In my case, I am using this on the page where I want to display the ruby + JS code #{raw decode_entities configurable_page.js_for_body} with this line all the script that is saved in the db is rendered on the page. so all the changes I have to make in the db field not on the haml page. On the haml page I only use one line code to display all JS code that is available .
So before rendering the JS onto the page, I guess you would pass it through one of the templating engines I listed above?
0

There are a few way to do in order to pass data from Rails to JS, see the video here:

http://railscasts.com/episodes/324-passing-data-to-javascript?view=comments

Comments

0

Personally, I store the data in a hidden field in my view, then work with it with jQuery.

=form_for :user do |f|
  =f.hidden_field :id  

Then in javascript

$('document').ready ->
  alert $('#user_id').val()

Comments

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.