Javascript & Ajax Organization

Hey guys,

Before I start off, I'm a Rails newbie, so if there is an obvious
solution to this problem, let me know!

I have a simple, blog-like Rails project. In the routes, I have a users
resource with a nested posts resource. Now, this is all fine and dandy
if everything is generated with Ruby.

Now, if I add an Ajax layer over this, things seem to complicate quite a
bit. Say, if I want to perform some kind of request using jQuery, I need
to be able to know the appropriate path to perform this request on (ex,
users/1/post/new), but this requires me to generate this path
dynamically in the Rails script. If I have couple hundred users, this
would mean that each one of these users would have to have these paths
dynamically generated. The issue is, this is not so good when it comes
to bandwidth, download times, and so forth.

And so I thought, why not split off the posts resource and NOT make it
nested? That way, I could have paths like 'post/new', and collect the
user information via the request. This makes the project extremely
unclean, however. It's just not... pretty.

How can I handle this issue? What is the best way to approach it?

Thanks much!

Hi Mateusz,

...

Now, if I add an Ajax layer over this, things seem to complicate quite a
bit. Say, if I want to perform some kind of request using jQuery, I need
to be able to know the appropriate path to perform this request on (ex,
users/1/post/new), but this requires me to generate this path
dynamically in the Rails script.

Maybe I'm missing something but ... You say 'everything' is working
fine without Ajax which, to me, means that you already know the user
id and are sending it to the view when you render the 'new' view. The
user object is available to you in that view. So there are a couple
of 'easy' approaches to your problem. If you're doing a full page
render then you can do an erb substitution into the Ajax url in your
jQuery. If you'd prefer to grab the user id via jQuery for whatever
reason, you can put it in the page via a hidden_field_tag when you
render the form and use that to construct your Ajax url, perhaps by
binding a function to the .submit.

HTH,
Bill

Well, ideally I would like to have the views and javascripts split. I
don't want to embed any javascript within my view. Something like this:

http://bitprison.net/rails3_dynamic_javascript

This, however, will make each user have "their own" javascript, since it
has to be dynamically generated. Not ideal either.

You could also add the url in your erb template with a "data"
attribute on the form and then read it with javascript. If you really
don't want to generate the template with the URL encoded (though I
don't think that will be a huge performance problem), you could
probably also grab the ID from the current URL with javascript
(window.location).