0

Right now, I have some tooltip JavaScript that I'd like to run on every page of my app, but only if the current user's model has User.advanced_tooltips set to true in my database.

What is the best way conceptually to get this JavaScript to trigger conditionally based on a value in a database? I'm having some real trouble getting JavaScript and Rails to communicate.

1

3 Answers 3

1

You could do something like this, assuming you are using jquery:

<script type='text/javascript'>
$(document).ready(function() {
   var advtt = '<%= @user.advanced_tooltips ? "yes" : "no" %>';
   if ( advtt == 'yes')
     # ?? add css, or whatever
});
</script>

This assumes @user is set in the controller before rendering the view that contains the above Javascript.

2
  • That's how I normally track my user, in a before_filter that sets @user before each controller action. However, this project uses the session variable to store the current user's id, and -- since I jumped on this project's team mid-completion -- major refactoring isn't really an option. Nov 5, 2012 at 18:32
  • I don't see how that would require a major refactoring. All you need to do is replace @user.advanced_tooltips with User.find(session[:user_id]).advanced_tooltips, or whatever it is.
    – RadBrad
    Nov 5, 2012 at 18:39
1

A clean and simple solution is to wrap javascript functions in rails logic:

<script type='text/javascript'>

  var setupTooltips = function() {
    // do something here
  }

  $(document).ready(function() {

    <% if current_user.advanced_tooltips %>
      setupTooltips();
    <% end %>

  });

</script>
1
  • Unfortunately, this is what my initial attempt at a solution looked like. I tried both embedded the code in my layout (which worked until I rendered certain views in pop-up modals sans layout) and in a js.erb file (where it was apparently unable to access the session variable, which is how I'm storing the user) Nov 5, 2012 at 18:30
0

Here's the solution I ended up using (given the very weird constraints imposed by this project):

First, I set up a controller route that finds the current User and then renders its advanced_tooltip value as text.

Then, in my application.js, I made an AJAX call using $.get to that route, then checked whether the result == "true" to determine whether or not a user had advanced tooltips enabled.

It's a messy solution (and those listed above are actually better), but since I had some very rigid restrictions due to me jumping onto someone else's project's mid-completion, it's what I had to do.

Still gave both comment up-votes, as they're valid and would totally work under normal circumstances.

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.