Curso rails

1,263 views

Published on

0 Comments
1 Like
Statistics
Notes
  • Be the first to comment

No Downloads
Views
Total views
1,263
On SlideShare
0
From Embeds
0
Number of Embeds
6
Actions
Shares
0
Downloads
16
Comments
0
Likes
1
Embeds 0
No embeds

No notes for slide

Curso rails

  1. 1. Rails for real people @kurenn @rkrdo89 @icalialabs 1
  2. 2. Table of contents01 From bottom to top02 MVC to rule them all!03 Deep into the CRUD04 Sexy Validation05 Three or more is a crowd06 Rest in peace07 A bit of javaRails for real people 2
  3. 3. 1. From bottom to top 3
  4. 4. Creating rails app $ rails Usage: rails new APP_PATH [options] Options: -O, [--skip-active-record] -d, [--database=DATABASE] # Skip Active Record files # Preconfigure database # Default: sqlite3 -j, [--javascript=JAVASCRIPT] # Preconfigure JavaScript library # Default: jquery Runtime options: -f, [--force] # Overwrite files that already exist -p, [--pretend] # Run but do not make any changes Example: rails new ~/Code/Ruby/weblogFrom bottom to top 4
  5. 5. Creating rails app $ rails new nerd_blog create This will create the skeleton for a Rails app create Gemfile in a new nerd_blog directory create app create app/controllers/application_controller.rb create app/mailers create app/models create app/views/layouts/application.html.erb create config create log create public/index.html create script/rails run bundle installFrom bottom to top 5
  6. 6. Creating rails app $ rails new nerd_blog run bundle install Fetching source index for http://rubygems.org/ Installing rake (0.9.2) Using activesupport (3.1) Using rack (1.3.0) Using actionpack (3.1) Using actionmailer (3.1) Using activerecord (3.1) Using bundler (1.0.15) Installing coffee-script (2.2.0) Installing jquery-rails (1.0.12) Using rails (3.1) Installing sqlite3 (1.3.3) with native extensions Your bundle is complete!From bottom to top 6
  7. 7. Rails Commands $ cd nerd_blog $ rails Usage: rails COMMAND [ARGS] Lists commands The most common rails commands are: generate Generate new code (short-cut alias: "g") console Start the Rails console (short-cut alias: "c") server Start the Rails server (short-cut alias: "s") dbconsole Start a console for the db in config/database.yml (short-cut alias: "db") All commands can be run with -h for more information.From bottom to top 7
  8. 8. Starting the server $ rails server Starts a basic development server => Booting WEBrick => Rails 3.1 app in development on http://0.0.0.0:3000 => Call with -d to detach => Ctrl-C to shutdown server [2011-06-30 16:44:43] INFO WEBrick 1.3.1 [2011-06-30 16:44:43] INFO ruby 1.9.2 [2011-06-30 16:44:43] INFO WEBrick::HTTPServer#start: port=3000 http://localhost:3000 Shortcut $ rails sFrom bottom to top 8
  9. 9. Using generators $ rails generate Creates template files Usage: rails generate <GENERATOR> [args] Please choose a generator below. Rails: helper mailer migration Shortcut model scaffold $ rails gFrom bottom to top 9
  10. 10. Running the console $ rails console Loads the rails project console Loading development environment (Rails 3.2) > User.create(email: ‘user@example.com’) SQL (15.2ms) INSERT INTO "users" ("email") VALUES (?) [["email", “user@example.com”]] => #<User id: 1, email: “user@example.com”> Shortcut $ rails cFrom bottom to top 10
  11. 11. 2. MVC to rule them all 11
  12. 12. From the M to the C Database Model Actions MVC Controller Browser ViewMVC to rule them all! 12
  13. 13. Controllers in the wild $ rails g controller static_pages Creates a controller for static pages ‣ app/controllers/static_pages.rb class StaticPagesController < ApplicationController end Let’s add some actions WTF! class StaticPagesController < ApplicationController def home end def about end endMVC to rule them all! 13
  14. 14. Controllers in the wild $ rails g controller static_pages home about Rails generates a views directory with the same name as the controller to bind them Same concept for the actions and views You kidding me? def home ‣ config/routes.rb end get static_pages/home def about get static_pages/about endMVC to rule them all! 14
  15. 15. Views at sight ‣ app/views/layouts/application.html.erb ‣ app/views/static_pages/home.html.erb <!DOCTYPE html> <h1>Home page</h1> <html> <head> <p> You can find me in <title>NerdBlog</title> app/views/static_pages/home.html.erb </head> </p> <body> <%= yield %> </body> </html> The views are rendered or yielded into the application layoutMVC to rule them all! 15
  16. 16. Views at sight nerd_blog app views This is the main layout layouts application.html.erb Renders the home template static_pages home.html.erb Renders the about template about.html.erbMVC to rule them all! 16
  17. 17. Helping views out! ‣ app/views/layouts/application.html.erb ‣ app/views/static_pages/home.html.erb <!DOCTYPE html> <% provide(:title, "Home") %> <html> <h1>Pages#about</h1> <head> <title><%= full_title(yield(:title)) %></title> ‣ app/helpers/application_helper.rb </head> <body> module ApplicationHelper <%= yield %> def full_title(page_title) </body> "Blog | #{page_title}" </html> end end Helpers are intended to kill the logic in the viewsMVC to rule them all! 17
  18. 18. 3. Deep into the CRUD 18
  19. 19. Spicy models field type $ rails g model blog_post title:string content:text Creates a blog_post model BlogPost ‣ app/models/blog_post.rb class BlogPost < ActiveRecord::Base ... end Maps the class to the table in plural blog_posts id title content 1 Rails from scratch Lorem ipsum Lorem ipsum... 2 My first blog post Bacon ipsum Bacon ipsum Bacon ipsum... 3 How to make money Hipster ipsum Hipster ipsum Hipster ipsum...Deep into the CRUD 19
  20. 20. Create Read Update Delete bp = BlogPost.new Create bp.title = "Learning Rails from scratch" bp.save Read BlogPost.find(5) bp = BlogPost.find(5) Update bp.title = "Updating title" bp.save bp = BlogPost.find(5) Delete bp.destroyDeep into the CRUD 20
  21. 21. Spicy modelsBut before you start run the migrations $ rake db:create:all $ rake db:migrate We’ll come back later on thisDeep into the CRUD 21
  22. 22. Create - RUD Syntax bp = BlogPost.new bp.title = "Learning Rails from scratch" id, it gets the r set bp.save we n eve Notic e ically set auto mat Alternate Syntax bp = BlogPost.new(title: "My blog is awesome", content: Lorem ipsum...) bp.save BlogPost.create(title: "My blog is awesome", content: Lorem ipsum...)Deep into the CRUD 22
  23. 23. CRead - UD Syntax BlogPost.find(1) # Returns single blog post with id 1 BlogPost.find(1, 2, 3) # Returns an array of blog posts with id 1,2 and 3 BlogPost.all # Returns an array with all blog posts BlogPost.order(:created_at) # Returns an array of blog posts ordered by date of creation BlogPost.count # Returns the number of blog posts BlogPost.where(:status => "Draft") # Returns only blog posts on draft BlogPost.limit(5) # Only five records BlogPost.where(:status => "Draft").order(:created_at).limit(5) All chained up!Deep into the CRUD 23
  24. 24. CRUpdate - D Syntax bp = BlogPost.find(1) bp.title = "Learning Rails from scratch" bp.save bp = BlogPost.find(1) bp.attributes = { title: "My blog is awesome", content: Lorem ipsum... } bp.save bp = BlogPost.find(1) bp.update_attributes( title: My blog is more awesome, status: Published )Deep into the CRUD 24
  25. 25. CRUDelete Syntax bp = BlogPost.find(1) bp.destroy BlogPost.destroy_allDeep into the CRUD 25
  26. 26. REST - 7 actions HTTP Index GET ‣ app/controllers/blog_posts_controller.rb def index @blog_posts = BlogPost.all respond_to do |format| format.html # index.html.erb end end ‣ config/routes.rb get /blog_posts, to: blog_posts#indexDeep into the CRUD 26
  27. 27. REST - 7 actions PARAMS HTTP Show :id GET ‣ app/controllers/blog_posts_controller.rb def show @blog_post = BlogPost.find(params[:id]) respond_to do |format| format.html # show.html.erb end end ‣ config/routes.rb get /blog_posts/:id, to: blog_posts#showDeep into the CRUD 27
  28. 28. REST - 7 actions HTTP New GET ‣ app/controllers/blog_posts_controller.rb def new @blog_post = BlogPost.new respond_to do |format| format.html # new.html.erb end end ‣ config/routes.rb get /blog_posts/new, to: blog_posts#newDeep into the CRUD 28
  29. 29. REST - 7 actions HTTP Create POST ‣ app/controllers/blog_posts_controller.rb def create @blog_post = BlogPost.new(params[:blog_post]) respond_to do |format| if @blog_post.save flash[:notice] = Blogpost was successfully created. format.html { redirect_to(blog_posts_path) } else format.html { render "new" } end end end X ‣ config/routes.rb post /blog_posts, to: blog_posts#createDeep into the CRUD 29
  30. 30. REST - 7 actions PARAMS HTTP Edit :id GET ‣ app/controllers/blog_posts_controller.rb def edit @blog_post = BlogPost.find(params[:id]) respond_to do |format| format.html # edit.html.erb end end ‣ config/routes.rb get /blog_posts/:id/edit, to: blog_posts#editDeep into the CRUD 30
  31. 31. REST - 7 actions HTTP Update PUT ‣ app/controllers/blog_posts_controller.rb def update @blog_post = BlogPost.find(params[:id]) respond_to do |format| if @blog_post.update_attributes(params[:blog_post]) flash[:notice] = Blogpost was successfully updated. format.html { redirect_to(@blog_post) } else format.html { render "edit" } end end X end ‣ config/routes.rb put /blog_posts/:id, to: blog_posts#updateDeep into the CRUD 31
  32. 32. REST - 7 actions HTTP Destroy DELETE ‣ app/controllers/blog_posts_controller.rb def destroy @blog_post = BlogPost.find(params[:id]) @blog_post.destroy respond_to do |format| format.html { redirect_to(blog_posts_path) } end end X ‣ config/routes.rb delete /blog_posts/:id, to: blog_posts#destroyDeep into the CRUD 32
  33. 33. Point the path and I’ll follow it Syntax‣ config/routes.rb $ rake routes get /blog_posts, to: blog_posts#index blog_posts GET /blog_posts(.:format) blog_posts#index get /blog_posts/:id, to: blog_posts#show GET /blog_posts/:id(.:format) blog_posts#show get /blog_posts/new, to: blog_posts#new blog_posts_new GET /blog_posts/new(.:format) blog_posts#new POST /blog_posts(.:format) blog_posts#create post /blog_posts, to: blog_posts#create GET /blog_posts/:id/edit(.:format) blog_posts#edit get /blog_posts/:id/edit, to: blog_posts#edit PUT /blog_posts/:id(.:format) blog_posts#update put /blog_posts/:id, to: blog_posts#update DELETE /blog_posts/:id(.:format) blog_posts#destroy delete /blog_posts/:id, to: blog_posts#destroy blog_posts GET /blogposts(.:format) blogposts#index POST /blogposts(.:format) blogposts#create new_blog_post GET /blogposts/new(.:format) blogposts#new resources :blog_posts edit_blog_post GET /blogposts/:id/edit(.:format) blogposts#edit blog_post GET /blogposts/:id(.:format) blogposts#show PUT /blogposts/:id(.:format) blogposts#update DELETE /blogposts/:id(.:format) blogposts#destroy Rails flavorDeep into the CRUD 33
  34. 34. 4. Sexy Validations 34
  35. 35. U shall not pass!‣ app/models/blog_post.rb class BlogPost < ActiveRecord::Base attr_accessible :content, :title validates_presence_of :title end $ rails console > bp = BlogPost.new => #<BlogPost id: nil, title: nil, content: nil> > bp.save => false > bp.error_messages => { title: ["cant be blank"] }Sexy Validation 35
  36. 36. U shall not pass! validates_presence_of :title validates_numericality_of :words_count validates_uniqueness_of :email validates_confirmation_of :password validates_acceptance_of :terms validates_format_of :email, with: /A[w+-.]+@[a-zd-.]+.[a-z]+z/i . . . And many many more...Sexy Validation 36
  37. 37. http://api.rubyonrails.org/ 37
  38. 38. Gemfile and Bundler‣ Gemfile source https://rubygems.org source https://rubygems.org $ bundle install gem rails, 3.2.12 gem rails, 3.2.12 gem sqlite3 $ rails g foundation:install gem sqlite3 # Gems used only for assets and not required # Gems used only for assets and not required # in production environments by default. # in production environments by default. group :assets do group :assets do gem sass-rails, ~> 3.2.3 gem sass-rails, ~> 3.2.3 gem coffee-rails, ~> 3.2.1 gem coffee-rails, ~> 3.2.1 gem uglifier, >= 1.0.3 gem uglifier, >= 1.0.3 gem zurb-foundation, ~> 4.0.0 end end gem jquery-rails gem jquery-rails # To use debugger # To use debugger gem debugger gem debuggerSexy Validation 38
  39. 39. http://foundation.zurb.com/docs/rails.html 39
  40. 40. 5. Three or more is a crowd 40
  41. 41. A BlogPost has many comments A Comment belongs to a BlogPost ‣ app/models/blog_post.rb ‣ app/models/comment.rb class BlogPost < ActiveRecord::Base class Comment < ActiveRecord::Base has_many :comments belongs_to :blog_post end end Plural Singular blog_posts id title content 1 Rails from scratch Lorem ipsum Lorem ipsum... 2 My first blog post Bacon ipsum Bacon ipsum Bacon ipsum... 3 How to make money Hipster ipsum Hipster ipsum... comments id content blog_post_id 1 It’s awesome 1 2 U shall not pass! 2Three or more is a crowd 3 Sucks! 3 41
  42. 42. AWhat about then? BlogPost has many comments> bp = BlogPost.find(1) => #<BlogPost id: 1, title: ‘Hello World’, content: ‘Lorem ipsum...’>> c = Comment.create(content: ‘It works!’, blog_post: bp) => #<Comment id: 1, content: ‘It works!’, blog_post_id: 1>> c.blog_post => #<BlogPost id: 1, title: ‘Hello World’, content: ‘Lorem ipsum...’>> c.blog_post.title => “Hello World”> bp = BlogPost.find(1) => #<BlogPost id: 1, title: ‘Hello World’, content: ‘Lorem ipsum...’>> bp.comments.count => 1> bp.comments =>[#<Comment id: 1, content: ‘It works!’, blog_post_id: 1>] Three or more is a crowd 42
  43. 43. What about then? Using the belongs_to/has_many association, Rails provides construct methods Method Purpose comment.blog_post Return the blog post associated to the comment blog_post.comments Return an array of the blog post’s comments blog_post.comments.create(args) Create a comment(blog_post_id = blog_post.id) blog_post.comments.build(args) Return a new comment instance(blog_post_id = blog_post.id)Three or more is a crowd 43
  44. 44. 6. REST in peace 44
  45. 45. Let’s comment out $ rails g controller Comments index new show edit ‣ app/config/routes.rb resources :comments resources :blog_posts do $ rake routes resource :comments end A little bit more restfulREST in peace 45
  46. 46. Controlling comments ‣ app/controllers/comments_controller.rb def create @blog_post = BlogPost.find(params[:blog_post_id]) @comment = @blog_post.comments.build(params[:comment]) if @comment.save redirect_to blog_post_path(@blog_post_path), flash: { notice: Your comment was posted} else redirect_to blog_post_path(@blog_post_path), flash: { error: Failes to post your comment, ja!} end end1. We first fetch the blog post from the blog_post_id2. Then build the comment through the blog post3. Finally save the comment and redirectREST in peace 46
  47. 47. And the views apa! ‣ app/views/blog_posts/show.html.erb <%= form_for [@blog_post, @comment] do |f| %> <div id="fields"> <%= f.label :content %> Renders like this <%= f.text_area :content %> </div> <div id="actions"> <%= f.submit Post %> </div> <% end %> Because our resources are nested we need the blog post for the comment controller to find it in the create action through the blog_post_idREST in peace 47
  48. 48. More on helpers! form_for(record, options = {}, block) text_field(object_name, method, options = {}) submit(value = nil, options = {}) truncate(text, options = {}) pluralize(count, singular, plural = nil) titleize(word) time_ago_in_words(from_time, include_seconds = false) number_to_currency(number, options = {})REST in peace 48
  49. 49. 7 A bit of java . 49
  50. 50. Let’s have a bit of ajax I will respond to javascript ‣ app/views/blog_posts/show.html.erb <%= form_for [@blog_post, @comment], remote: true do |f| %> ... <% end %> ‣ app/controllers/comments/comments_controller.rb respond_to do |format| if @comment.save format.html { redirect_to blog_post_path(@blog_post_path)... format.js else format.html { redirect_to blog_post_path(@blog_post_path)... end end ‣ app/views/comments/create.js.erb $(#comments).append(<%= j render(@comment) %>); $(form).reset();A bit of java 50
  51. 51. Let’s have a bit of ajax‣ app/views/comments/create.js.erb $(#comments).append(<%= j render(@comment) %>); $(form).reset(); The underscore means to render a partial‣ app/views/comments/_comment.html.erb <div class="comment"> <%= comment.content %> </div>‣ app/views/blog_spots/show.html.erb <div id="comments"> <%= render @blog_post.comments %> Rails identify if object is an array or a single </div> object when rendering like thisA bit of java 51
  52. 52. http://railscasts.com/ 52
  53. 53. http://api.rubyonrails.org/ 53
  54. 54. http://www.codeschool.com/ 54
  55. 55. http://ruby.railstutorial.org/ 55
  56. 56. http://guides.rubyonrails.org/ 56

×