1

Possible Duplicate:
Using Ruby variable in Javascript (In App View)

is there a way to create a kind of variable in a Ruby on Rails view to use it later in a javascript tag?

I want to do something like that:

    <p>
    <%  test=Build.where("result = 1").count(:result) %> of the builds succeeded.
    </p>


<%= javascript_tag do %>

            console.log(test);

<% end %>

Is there a way to do that? This is not working. Thanks in advance!

2
  • 1
    console.log(<%= test %>); The variable is in eruby context, not JS. Be sure to quote it unless it is a numeric value. Commented Dec 14, 2012 at 17:34
  • Oh, thanks, sorry I thought I already tried that! It works for my bigger problem I guess! Commented Dec 14, 2012 at 17:38

2 Answers 2

3

I would move the logic into the controller if possible, take a look at the gon gem too: https://github.com/gazay/gon

Edit: I read your question wrong.

# Controller
@test = Build.where("result = 1").count(:result)

# View
<%= javascript_tag do %>

    console.log(<%= @test %>);

<% end %>
Sign up to request clarification or add additional context in comments.

Comments

2

You can access any ruby variable in an erb with <%= %>

Since you want to show it as a string do

console.log('<%= Build.where("result = 1").count(:result) %>');

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.