Upgrade to Pro — share decks privately, control downloads, hide ads and more …

Learn a Little Rails

Learn a Little Rails

Presented at Detroit Dev Day 2016.

Amber Conville

November 12, 2016
Tweet

More Decks by Amber Conville

Other Decks in Programming

Transcript

  1. The Rails Philosophy • Opinionated • Convention over configuration •

    DRY (Don't Repeat Yourself) • less code means it's easier to maintain & modify • Test Driven Development (TDD) • Minimal code - maximal effect
  2. rails new suggestotron rails new creates a new Rails project

    with the name you give. In this case we told it to create a new project called suggestotron. Getting Started
  3. You can see that rails new created a lot directories

    and files. The ones we want to focus on today are: Getting Started File/Folder Purpose app/ Contains the controllers, models, and views for your application. You will do most of your work here. config/ Configure your application's runtime rules, routes, database, and more. db/ Shows your current database schema, as well as the database migrations. public/ The only folder seen to the world as-is. If you put files in here, they will be served directly without any processing by Rails. app/assets/ This is where your images, JavaScript, stylesheets (CSS), and other static files should go. Modern Rails apps use something called the Assets Pipeline, which combines all the JavaScript and CSS files in this directory into a single file for speediness.
  4. rails server Point your web browser to: http://localhost:3000 See your

    web app actually running! Running Your Application Locally
  5. rails generate scaffold topic title:string description:text generate scaffold tells Rails

    to create everything necessary to get up and running with topics. topic tells Rails the name of the new model. title:string says that topics have a title, which is a "string". description:text says that topics have a description which is a "text". (What's the difference between "string" and "text"? Basically "text" is for strings that might be very long.) Scaffolding a Model
  6. rake db:migrate This tells Rails to update the database to

    include a table for our new model. Scaffolding a Model
  7. Rake rake (ruby make) is a tool that allows you

    to run small Ruby programs (tasks) that you use often in your application. Here, rake db:migrate is a task provided by the Rails framework. It uses the migration file we just created (db/migrate/201xxxxxxxxxxx_create_topics.rb) to change the database. Scaffolding a Model
  8. At the core, most database driven web sites are the

    same. They need to store records and provide a way to do the following: • Create new records in the database • Read or show the records in the database • Update existing records • Destroy or delete records Because these 4 actions (CRUD) are so common, Rails includes the scaffold command to make creating them easier. CRUD With Scaffolding
  9. Point your browser to: http://localhost:3000/topics You should see the "Listing

    topics" page with headers for title and description, and a link to add a new topic: CRUD With Scaffolding
  10. • Click "New Topic" • Fill in the form and

    click "Create Topic" • You should see a page showing your new topic with a message that your topic was successfully created: CRUD With Scaffolding
  11. Click "Back" You should see the topic list again, this

    time with your new topic listed. There’s also "Show", "Edit", and “Destroy" links for each topic. CRUD With Scaffolding
  12. How did all those pages get created and hooked together?

    The Rails scaffold did it for you. Let's take a closer look at some of the files Rails created: app/models/topic.rb This file contains code for our topic model. If you look at it, it's nearly blank. Creating, reading, updating, and deleting records are built into Rails. CRUD With Scaffolding
  13. app/views/topics This folder contains all the views for our topics

    model. This is where the code for the forms is stored. Rails created all of these pages as part of the scaffold. CRUD With Scaffolding
  14. app/views/topics/show.html.erb This is the page you get when you click

    the "Show" link on the "Listing topics" page. app/views/topics/new.html.erb This is the page you get when you click "New Topic". CRUD With Scaffolding
  15. app/views/topics/edit.html.erb This is the page you get when you click

    "Edit". app/views/topics/_form.html.erb You may have noticed that the page for new topics and the page to edit topics looked similar. That's because they both use the code from this file to show a form. This file is called a partial since it only contains code for part of a page. Partials always have filenames starting with an underscore character. CRUD With Scaffolding
  16. app/controllers/topics_controller.rb This is the controller file that Rails created as

    part of the scaffold If you look, you'll see a method (a line beginning with def) for each of the views listed above (except _form.html.erb) CRUD With Scaffolding
  17. • root 'topics#index' is a Rails route that says the

    default address for your site is topics#index. topics#index is the topics list page (the topics controller with the index action). • Rails routes control how URLs (web addresses) get matched with code on the server. Similar to how addresses match with houses and apartments. • The file config/routes.rb is like an address directory listing the possible addresses and which code goes with each one • routes.rb uses some shortcuts so it doesn't always show all the possible URLs. To explore the URLs in more detail we can use the terminal. Setting the Default Page
  18. At the terminal, you can type rake routes, and you

    should get something that looks like this: $ rake routes
 Prefix Verb URI Pattern Controller#Action
 topics GET /topics(.:format) topics#index
 POST /topics(.:format) topics#create
 new_topic GET /topics/new(.:format) topics#new
 edit_topic GET /topics/:id/edit(.:format) topics#edit
 topic GET /topics/:id(.:format) topics#show
 PATCH /topics/:id(.:format) topics#update
 PUT /topics/:id(.:format) topics#update
 DELETE /topics/:id(.:format) topics#destroy
 root GET / topics#index This shows all the URLs your application responds to. The code that starts with colons are variables so :id means the id number of the record. The code in parenthesis is optional. Setting the Default Page
  19. You can also get this information on your site in

    development by going to http://localhost:3000/rails/info. You'll see something like this: You'll also see that table in Rails whenever you try to access an invalid route (try http://localhost:3000/sandwich) Setting the Default Page
  20. Exploring Routes (optional) Now you can have a look at

    the paths that are available in your app by using rails console in the terminal: $ rails console
 >> app.topics_path
 => "/topics"
 
 >> app.topics_url
 => "http://www.example.com/topics" app is a special object that represents your entire application. You can ask it about its routes, play with its database connections, or make pseudo-web requests against it with get or post (and lots more). Setting the Default Page
  21. • Just like before, we're creating a new model named

    "vote" • The only thing really different is the integer we added called topic_id. • topic_id is the data we need to draw the line between votes and topics. • We didn't generate a full scaffold this time because we aren't going to do the full CRUD for votes; they're just going to be considered part of topics as-is. Voting On Topics
  22. Teach the Topic model about Votes app/models/topic.rb class Topic <

    ActiveRecord::Base
 has_many :votes, dependent: :destroy
 end Hooking Up Votes And Topics
  23. Teach the Vote model about Topics app/models/vote.rb class Vote <

    ActiveRecord::Base
 belongs_to :topic
 end Hooking Up Votes And Topics
  24. You can access these models form within rails console See

    how many topics exist: Topic.count Save the first topic into a variable: my_topic = Topic.first Hooking Up Votes And Topics
  25. Change the title of that topic to something else: my_topic.update_attributes(title:

    'Edited in the console') Add a vote to that topic: my_topic.votes.create Hooking Up Votes And Topics
  26. See how many votes that topic has: my_topic.votes.count Remove a

    vote from that topic: my_topic.votes.first.destroy Hooking Up Votes And Topics
  27. ActiveModel will create all of these methods for you. Hooking

    Up Votes And Topics Model class / association methods Topic.first Topic.last Topic.all Topic.count Topic.find_by_id(5) Topic.destroy_all my_topic.votes.count my_topic.votes.create my_topic.votes.destroy_all Model instance methods my_topic.title my_topic.title = 'New title' my_topic.update_attributes
 (title: 'New title') my_topic.save my_topic.save! my_topic.destroy my_topic.votes.first.destroy
  28. Add a new controller action for voting app/controllers/topics_controller.rb def upvote


    @topic = Topic.find(params[:id])
 @topic.votes.create
 redirect_to(topics_path)
 end @topic = Topic.find(params[:id]) finds the topic in the database with that id and stores it in the variable @topic. @topic.votes.create creates a new vote for the current topic and saves it in the database. redirect_to(topics_path) tells the browser to go back to topics_path (the topics list). Allow People To Vote
  29. Add a new route for voting config/routes.rb resources :topics do


    member do
 post 'upvote'
 end
 end Allow People To Vote
  30. Add the button to the view app/views/topics/index.html.erb <% @topics.each do

    |topic| %>
 <tr>
 <td><%= topic.title %></td>
 <td><%= topic.description %></td>
 <td><%= pluralize(topic.votes.count, "vote") %></td>
 <td><%= button_to '+1', upvote_topic_path(topic), method: :post %></ td>
 <td><%= link_to 'Show', topic %></td>
 <td><%= link_to 'Edit', edit_topic_path(topic) %></td>
 <td><%= link_to 'Destroy', topic, method: :delete, data: { confirm: 'Are you sure?' } %></td>
 </tr>
 <% end %> Allow People To Vote
  31. • pluralize(topic.votes.count, "vote") displays the number of votes the topic

    has, plus the word "vote" or "votes" accordingly. • button_to '+1' creates an HTML button with the text "+1". • upvote_topic_path(topic) creates the appropriate URL for the action we want to invoke. In this case, we want to upvote the current topic. • upvote_topic_path(topic) would return /topics/42/upvote (if topic.id was 42) • method: :post ensures we do the create action of CRUD, not the read action. Allow People To Vote