a question about rails general practice with REST, json, and ajax
- by Nik
Hi all, I have this question concerning REST I think:
I have read a few rest tutorials and the feeling I get from them is that each action in a restful controller tends to be lean and almost single purpose:
"Index gives off a collection of a model
show gives off one model
edit/new a prep place for changing/create a model
update/create changes and makes new model
deletes removes one model"
After reading all these tutorials, rest seems to be to be a means to create an interface for a model, much like active resource type of thing. the mantra seems to be "controller provides data and data only and is also pretty convention over configuration, so expect projects_path to return a bunch of projects"
I can understand that, and I like the cleanliness. But here's when I run into some trouble in reality in applying these guidelines:
say three models, Project with attrib title, User with attrib name, and Location with attrib address.
Say in views/users/index.html.erb, I want to use Ajax to fetch and display a project in a div#project_display when the user clicks on a project element, I know that I can use views/projects/show.js.rjs like this:
page.replace_html 'project_display' "#{@project.name}"
where in the projects_controller.rb
def show
@project = Project.find(params[:id])
repsond_to do |format|
format.js
and other formats...
end
end
I have no problem in doing that for a couple of years now. BUT doesn't that mean that my JS response for the project#show action is LOCkED to present data to div#project_display element and show only whatever I that rjs template says it should show? That's very limiting and doesn't sound very "interface" like.
I have never used JSON before or much XML, so I thought, maybe the JS response should send back raw stuff, like JSON and somehow the page on which the ajax request was called has the instruction on what do to with these raw data. That sounds a lot more flexible, doesn't it? Because look back at that exmpale, what if in the views/locations/index.html.erb, I want to do the exact same thing except I want to put the response in div#project_goes_here and the response should be #{project.name} I know this is a trivial change but that's the point: the RJS only allows one template at a time.
So I think the JSON route is the way to go, but how does the already loaded page, the one that the ajax call came from, know when or how to "look forward" to incoming data?
I read that PrototypeJS has this template thing, I wouldn't mind using it with JSON, but if you can demonstrate this or other means for displaying received-from-ajax data, I am all attention.
Thank You