#325 Backbone on Rails Part 2 pro
In the second part of this two part series on Backbone.js, we finish up the Raffler application. Included is how to create entries through a form, respond to events, extract sub-views, pre-populate records, visit routes, and more.
- Download:
- source code
- mp4
- m4v
- webm
- ogv
I never worked with backbone.js, but it seems to me that rails is a bit heavy when you skip most of the rails functionality. Would it not be better to use sinatra or even not use ruby at all? I guess you could use node.js?
testing backbone.js tutorial
Thanks Ryan for all the work on these screencasts.
Thanks for that link on testing! pretty useful...
And I'd like to hear Ryan's POV on moving away from Rails if you're leveraging MVC on the client. I agree that rails seems a bit overkill for single page/web2.0 app (like Trello).
To push your point further - it almost felt like extra work to use server validations in this episode.
+1
Except the server validations, I think that's pretty useful information ;)
You definitely could. Still, in my experience, whenever I try to go light-weight, I realize how much Rails does for you, without you even knowing it. Like ActiveRecord integration with all kinds of handy tasks, CSRF protection, the asset pipeline, a rich set of gems/plugins, hundreds of helpers in controllers and views, and so on. What I'm trying to say is: Sinatra and Node.js are awesome tools, but be sure to know what you're getting yourself into. :)
This has been my experience as well. I've tried to move away from Rails in favor of a lighter weight solution on a number of occasions. Each time I've ended up migrating back to Rails at some point because of some feature(s) it gave me out of the box, or for some feature(s) provided by a plugin/ gem designed to work with Rails. The two biggies in the last project I did this with were the asset pipeline, which works really nicely with Backbone (especially with the eco template gem), and Devise for authentication.
Hi Elliot,
I am just about to embark on this exact same thing. Do you have any code examples you could share with regards to logging in with Devise /Backbone?
Any help would be greatly appreciated.
Kind regards,
Luke Byrne
Hello Luke and Elliot,
Do you have any pointers as to how to set Devise authentication on an existing rails app with backbone.js?
Thank you!
Mauricio,
I have an existing rails app that uses devise and I want to connect to it using backbone.js from another app.
Were you able to obtain any feedback as to the best way to go about this?
Kind regards
Andrew
What a great episode - thank you !!
I'd like to see more episodes on Backbone - like:
- handling associations between models in a Backbone app
- caching data using localStorage
- using multiple view objects and multiple routers
- appCache and Backbone
- testing with Jasmine and Sinon
+1 for jasmine
+1 for testing (Jasmine, Evergreen perhaps?)
+1 for evergreen because it use jasmine with coffeescript
+1 for handling associations!
+1 I really want to know how to use multiple view
+1 for handling associations
Awesome job, Ryan!
I found as I started integrating this into existing applications that if I have a large number of datasets, it tries to load all of the data at the initial load. This is because each router is loaded in the base window.App class. Is this how it is supposed to work? I don't expect you to answer this, but if someone can respond, I would appreciate it.
Also, I would love to see a screencast that covers pagination with Backbone.js.. It seems that there is very little documentation on this and it is very complicated to understand. If you could dumb that down for us, I would really appreciate it!
This was great! I (think I) know backbone and this episode had tons of useful extras that either taught me something new, or really solidified a concept - priceless!:
Here's suggestions for Part 3:
I agree with the previous comments.
It would be very nice to see this series continue with new episodes!
Keep up the good work!
I really want see next episode about backbone. When I started using backbone with rails I have big problems with rails associations and with more then one backbone router
Made my head hurt... but really great functionality.
It would be interesting to see this in conjunction with the offline app. It seems a whole client side application could persist and pull application updates from the main server when they are available. Potentially sync data, but really have everything live on the client indefinitely... making the web server a software distribution technology and data store rather than an application server technology. This would work wonders for scale.
+10 on what you just said.
Probably start changing how we see and think about web servers with js gaining this kinda speed.
Thank you for the useful episodes Ryan.
I found it cleaner to use haml_coffee_assets as the template engine as you don't need to write your Html code using javascript. and you can simply use coffeescript inside your haml templates :)
Thanks Shamim! I was just searching around for some way to keep my views in HAML.
Thanks from me also. The templates look allot cleaner now.
Thanks a lot! Lifesaver.
Hello, nice screencast, Thanks!!
Do you know where can I find a nested resources example with backbone?
I want to "nest" entries to users like this: users/:user_id/entries and show them into that nested url (not into users/:user_id).
Hi,
I did a variant of the above Raffler in Spine JS to find out the differences between Spine JS and Backbone. For those of you that are interested, the result can be found here: https://github.com/ygor/spine-raffler
The only thing that I have not been able to figure out yet is how to do the remote validation. Let me know what you think!
I'm doing ExtJs for some time and bumped to similar problem, at beginning, cause I was lazy to rewrite validation to client side. Then I realized that VALIDATION is not same as BUSINESS RULES in your app.
There is nothing wrong having same validation in UI. It will just prevent UI to make unnecessary round trips to backend. So add that validation in UI. Also, you can pass exceptions for Business rules back to ui by packing exception as nice messages which you can send with HTTP 4xx or 5xx status codes. Or you can add special JSON/XML node which your javascript code will handle before response reaches your UI model.
After all, UI validation is always more restrictive than one which is in service ;)
What Textmate bundle do you use for .eco files ? I notice the bottom of your textmate window says javascript template. Where can I get it?
No need now. I'm using the Haml_Coffee_Assets gem referenced above. Textmate treats the hamlc files just like haml
Is there any reason to not use the fat arrow (=>) for every method definition in your classes?
These 2 screencasts was really amazing Ryan.
Thank you very much for that stuff.
I always love your clarity (sometimes it's still very complicated though, even if you try to make it as simple as possible ;))
What I don't like with backbone is that you can't generate your forms based on your backend models (as simple_form does it for you)...
Any Idea ?
Great screencast, Ryan. I have been toying around with Backbone and Ember. I hope you do a screencast on ember. I think it is interesting to contrast the end user development strategies between Ember and Backbone. Both libraries offer similar benefits, but are used in pretty different ways.
I like backbone, but being a Rails guy, I think I prefer the approach Ember takes.
Made our heads hurt the first time but made a lot more sense after watching it again! Great work.
We found that it pairs up nicely with the Backbone Codeschool course, which let you play with the individual MVC components one by one, and then your Railscasts show the overall architecture of a Backbone app and how the individual bits come together.
There seem to be a few interesting Backbone plugins springing up in the community - Marionette, LayoutManager, ModelBinding and Forms to name just a few we've come across - any chance of a screencast covering some of these?
I've been using Marionette for 6+ months in a production app of around 700+ JS files. It goes together with Backbone like peanut butter jelly :-)
Marionette reduces a ton of the Backbone boilerplate stuff you see in virtually every tutorial / screencast. Marionette's docs are great but there's been a lack of real world use cases / screencasts about it - until recently. Check out MarionetteJS for several good links or BackboneRails.com since you're probably looking to see a scalable app built alongside Rails.
Hope this helps!
At 9:49, my response.responseText contained
{"name":["can't be blank"]}
and not
{"errors": {"name":["can't be blank"]}}
(i.e. there was no "errors" key).So when parsing the messages within entries/index.js.coffee#handleError method, I did
instead of
I have rails 3.1.2, and my web browser is Chrome 16.0.912.77.
Got Rails 3.2 here and no problems at all. Maybe this?
YES! Thank You. I also have 3.1.2 and was not working for me.
Does your config/application.rb file have this?
config.assets.initialize_on_precompile = false
I'm having a bunch of trouble trying to make this work beyond what has been said on both screencasts.
I'm simply trying to make a full CRUD, like Rails scaffold, just work. But I'm getting bite by loading times and page rendering.
Anybody else having such problems?
Too complicated for a simple app :(
Why did it trigger an alert function when he clicked each entry (triggering "showEntry" and a new url opened?
Hi I'm wondering if anybody else ran into the problem with drawWinner()
I'm getting the error
Uncaught TypeError: Cannont call methoed 'drawWinner' of undefined.
I've gone back over the code above and copied and pasted it but still no luck. Any ideas?
Thanks
Linda
Could it be due to CoffeeScript space vs. tab?
You reminded me to doublecheck my whitespaces. Thanks.
Thanks for the simple contribution! I've never messed with coffescript before and I'd have had no idea that spaces instead of tabs would mess my code up so much!
Thanks Ryan. I started typing out two issues I was having before I did a thorough check of tabs vs. spaces in my coffee file. A quick convert to my preferences fixed both. All, just be careful about this if you get totally unexpected, weird errors :).
When I write "tagName: 'li'" im stuck with an error?
Error: Parse error on line 5: Unexpected '{'
(in /rails_projects/raffler/app/assets/javascripts/views/entries/entry.js.coffee)
How would I change the templates to use Handlebars? I've tried using 'handlebars_assets'. But I'm getting odd errors. Any chances to see versions of /templates/entries/entry.jst.hbs and index.jst.hbs?
I've done a mashup of this rails cast with railscast 295 but changed to use Handlebars instead of Mustache.
Check it out:
https://github.com/etewiah/sharing_handlebars_templates_in_backbone
I am having a problem though with using exactly the same template on both the client and the server. I explain better in the README. Any comments will be appreciated.
Thanks
RailsConf this year had a good talk on Backbone
Thanks Ryan. I'm a new one so permit me to imagine:
Ruby is excellent for oo( object oriented) language. With oo db,such as mongodb, programming will be much more productive.
I love rails, but I think his power is in activerecord. Since relation db is obsoleteļ¼ rails' value is limited. So
{new :old}
ruby/javascript :java
mongodb :mysql
json :xml
(things like)BB :rails
REST:SOAP
Is my understanding right?
Im getting an error on the validation server side... in fact Im not getting the error alert when the name is not present.
im using rails 3.2.8 and backbone-on-rails 0.9.2.3
In the network console it does state that theres an error with the api/entries, and in the response theres the errors key, but still no alert..
Got it... I had an indentation problem...
Last few seconds of this talk appears to be cut off as well.
1) Not be amiss to add csrf token in your backbone forms and turn it on in application controller:
That works fine but I doubt that it is really necessary because browsers have ajax crossdomain restrictions anyway.
I am right or not?
2) I just found it handful when you have multiple fields in your forms use backbone-syphon-rails gem. It doing form serialisation for you and you can write something like that:
I'm surprised there were no comments about issues with adding an entry. This took me sometime to figure out so posing here.
I was getting a 500 error when trying to add a name entry:
I guess in rails 4 some extra parameter requirements are needed:
more info here:
http://stackoverflow.com/questions/17868427/rails-4-activemodelforbiddenattributeserror
http://edgeapi.rubyonrails.org/classes/ActionController/StrongParameters.html
Here's my implementation of the fix. Let me know if I overlooked something and this is not really needed please!
In entries_controller.rb
I was able to use strong parameters on the create action successfully.
But unfortunately, I am getting an error from the update action when trying to save the selected winner to the database. Rails is saying "wrong number of arguments (1 for 2). I've tried many google searches to no avail, I would appreciate anyone's help with this.
Thanks!
I did
def update
respond_with Entry.find(params[:id]).update_attributes(entry_params)
end
private
def entry_params
params.require(:entry).permit(:name, :winner)
end
Adding:
into my entries_index.js.coffee file under createEntry causes an
My log has this:
Any thoughts?
I was able to fix the ExecJS error. Had to do with having spaces instead of tabs in my coffeescript function.
I'm still just a little confused about the #container div. There is no #container div in the template, so why and how does that work? Just looking for clarification.
The #container div is in an erb template (/app/views/main/index.html.erb). The root route in /config/routes.rb points to the main controller's index action, which loads this erb template.
with the latest versions , the event.preventdefault() does not seem to make any difference,any ideas?