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.

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

2 Comments

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.
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.
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 Comment

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)
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.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.