Reputation: 11
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
Upvotes: 1
Views: 123
Reputation: 1554
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:
Upvotes: 1
Reputation: 2276
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()
Upvotes: 0
Reputation: 4549
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
Upvotes: 0