Search code examples
jqueryruby-on-railsvariablesjrails

How to transmit a Rails variable to the jQuery function?


I'm making very simple ROR (rails 2.3.5) application and using jQuery plugin jRails. The idea is to lunch modified in jQuery youtube player, which will play random videos from ror's controller's list.

controller.rb

    def show
    @clip = Video.find(:all, :select =>'link', :order => 'RANDOM()', :limit => 1).map(&:link)
    respond_to do |format|
      format.html 
     end
  end

show.html.erb

<div id="random">
<%=@clip%>
</div>

The link here is just a random youtube link for example. The question for lame me is how to get this variable in this jQuery function?

application.js

 $(document).ready(function(){
    $('#player').youTubeEmbed("http://www.youtube.com/watch?v=ZDFlmxmBne8")

});

Would be very thankful for any help.


Solution

  • Leave your rails code as is and in jQuery use:

    $(document).ready(function(){
      $('#player').youTubeEmbed($('#random').text())
    });
    

    For enhanced accessibility I'd change the erb to:

    <div id="random">
    <%=link_to h(@clip), h(@clip) %>
    </div>
    

    and then the js:

    $(document).ready(function(){
      $('#player').youTubeEmbed($('#random a').attr('href'));
      $('#random').hide();
    });