In part i of the Sproutcore + Rails series I described how to query information from a rails server and display it within a Sproutcore application. In part ii I explained how to wire the other basic CRUD operations together.
In both posts I mentioned that the REST API employed by SproutCore wasn't really RESTful, and that I expected that would be fixed before SproutCore v1.0. I couldn't resist it and eventually submitted some changes myself to make SproutCore behave RESTfully. Check out SproutCore edge.
The result is that now in Rails you simply do what you're used to. I.e., in your routes file you do for example:
ActionController::Routing::Routes.draw do |map|
map.with_options(:path_prefix => "sc") do |m|
m.resources :companies, :contacts, :projects, :tasks
end
end
Notice that all resources must be put before a path_prefix so that you can develop/test in combination with the sproutcore server which proxies to the rails server. In production this path_prefix isn't necessary, if you compile your SC app with the sc-build tool. Furthermore, some resources might also need to output XML, HTML, etc. so you'd want to actually define the resources in the root of Routes. To keep things DRY this is what I actually do:
def draw(map)
map.resources :contacts,
:collection => {:archive => :delete},
:member => {:upgrade => :put}
map.resources :projects, :has_many => :tasks
map.resources :companies, :contacts
#map.connect ':controller/:action'
end
ActionController::Routing::Routes.draw do |map|
draw(map)
unless ENV['RAILS_ENV'] == 'production'
map.with_options(:path_prefix => "sc") { |m| draw(m) }
end
end
So I add my routes to the draw method like I normally would and then they are hosted under both the root of Routes and under path prefix sc at the same time in development and test mode. Note that the order of the statements within the Routes.draw block is important if you want to use the generated routes methods, like for example: :url => edit_contact_path(contact), which in development and test mode would result in for example: :url => '/sc/contacts/12345/edit'.
That's awesome! I was just wondering how to do this. Great work!
— Mike Subelsky on August 5, 2008 at 5:26 pm #
...also note that you'll need to change your core.js file to read "SC.RestServer.create" not "SC.Server.create"
— Mike Subelsky on August 5, 2008 at 6:48 pm #
Is it possible to release a tarbal of the source of the working rails - sc example. I got kinda lost during the second tutorial, e.g. where to put the rails auth token, how to actually implement the saving of the contacts etc.
Thx a lot and keep up the good work!
— Kevin on August 6, 2008 at 11:18 am #