Using Rails Objects in js file

Hey guys,

This seems pretty simple, but I cannot seem to find an answer online.
I have a user model and would like to use a user object in the js
file. Any ideas as to how I can do this?

Thanks and Regards.

Rails does not process js files directly.
I would do one of 2 things :-

  1. Output any data that you require from the user object into a script
    tag within the page that uses the javascript and pass that data
    through to your javascript code.

  2. Use rails RJS feature (see
    Layouts and Rendering in Rails — Ruby on Rails Guides
    and search for RJS)




Are you looking to manipulate your Rails models on the client side
without having the user reload the page? If so you need to find or
create a Javascript REST client, which isn’t all that hard. You can
use Prototype or jQuery’s Ajax helpers directly, or you could use a
javascript library. The best ones I’ve found are Backbone.JS and it’s
Model and Sync layer, or the no longer maintained Jester.JS from
thoughtbot inc. After figuring out how you are going to access your
models on the client side, you need to ensure your controllers are
RESTful and adhere to the standard rails routing principles. If you
don’t know what those are look at the “Rails Routing from the Outside
In” guide on the site. After doing this, make
sure your controllers can respond to requests in :json or :xml formats
so your javascript can interpret the data.

I would caution against using RJS because it is often murky generated
code, hard to maintain big amounts of, and ties you down to one
Javascript library (Prototype). My preferred way of interacting with
Javascript from the Rails side is by using one of the UJS drivers in
Rails 3 (I prefer jQuery). This way, you just add specific attributes
to your HTML, and the jquery-rails plugin handles the rest.

Let me know if any of this is unclear!