Rails/JQuery Collection Select

I may be asking a very dumb question, but I thought it’d be worth the asking…

I’m using JQuery to dynamically create some form fields for entering phone numbers… Basically just two fields… One for the number, and a select field so that the user can choose whether it’s a Home/Work/etc. number.

My Phone Number Categories (Home/Work/etc.) are stored in the database… Is there any way for JQuery to access the @phone_number_categories Rails variable from within the JavaScript code to create the select?

Joshua,

You can’t access that variable directly from jQuery because jQuery is Javascript running in the browser and @phone_number_categories is Ruby running on the server. If you want to do all this on the client side then you can save the categories into a Javascript variable that is in scope with the jQuery code. You can store them in an array or JSON object or an array of JSON objects or what ever makes the most sense.

Anthony Crumley

Joshua,

BTW…I forgot to mention there is a to_json method you can probably use to convert the @phone_number_categories collection to a Javascript value.

Anthony Crumley

Joshua,

Also consider using link_to_remote with the :update and :position options. Then you can keep all the view code on the server.

Anthony Crumley

Thanks Anthony! Your suggestion to use Rails’ to_json method was right on target…

I ended up creating a controller for the PhoneNumberCategory and added the to_json format on it’s index method. This way, my JQuery script can do a JSON request and then dynamically create a select based on the results. Then, when the user is ready to save, I get the phone numbers using the params, automagically populated by Rails…

Actually, my prior method was to use a link_to_remote, a partial, some controller methods to put an array of phone number hashes in the session, and other various things… But this was just way too much to maintain and was really kinda slow… I guess Rails has spoiled me in the fact that I’ve come to expect an easier way to do things - and coming from a Java/.NET background makes it all a bit of a vacation (:

Thanks again for your help - it’s people like you that make me excited about using/continuing to learn Rails! Bless you!