Monthly Archives: July 2013

Demystifying Rails – Models and the Database

In my previous post I wrote about the steps to creating your first route, controller and view in Ruby on Rails. Now I will talk about migrating the database and using models.

In your app, you will most likely want to use a database for something – either for inventory, user information, object information (like a database about movies or something). In this example, let’s say we’re building on our books app from the last example. What we will want to do first, in our terminal, is to create a database schema.

Step 1:  $ rails generate model book title:string description:text author:string

In this one line we are generating a new book model, which has three attributes – a title, a description, and an author, and we are specifying what kind of information those attributes will hold. (note you could say title without string, because the default is string).

This will create a few new files for you, including a database migration file in db/migrate, a book model in app/models and some testing files.

In db/migrate you can open up your migration file, and you should see a new class called CreateBooks with a method called ‘change’ which creates a table and the columns should be the attributes that you entered in the command line. If you forgot an attribute, or want to change one, you can do it in this file now.

In app/models you will see a Book model, which includes just a class called Book.

Step 2: $ rake db:create

Now, if your console says this already exists, that’s cool, now you go to step 3

Step 3: rake db:migrate

Now your table has been made in the database, and you can start populating it with information. How we did this to start out with was to start the rails console and enter them in there. Rails console is a Ruby environment you can use from your terminal.

Step 4: $ rails console

Note that to get out this you can just type quit.

In the rails console you can then add new things to your database, using commands like this:

Creating records

  • s = shirt.new
  • s.name = “daring fireball”
  • s.save

Finding records

  • s = Shirt.find(1)

Finding where id =1, this returns an instance

  • shirts = Shirt.where(:name => “xxxxx”)

returns an array of shirts

  • Shirt.where(“name like ?”, search)

Updating records

  • s = Shirt.find(1)
  • s.name = “ xxx”
  • s.save

VERY IMPORTANT: Note that nothing goes to the database unless you use the save command.

So I might do something like this

Step 5:  Add some data to your database through the Rails console (if you are a beginner anyway)

book = Book.new
book.title = "Alice in Wonderland"
book.description = "Some crazy stuff going on"
book.author = "Lewis Carroll"
book.save

Now, when you have created some books and saved them, then you should be able to refer to them within your rails app, by referring to the model. First you need to initialise the new Books model class in your welcome controller

Step 6: In WelcomeController’s index method enter
@books = Book.all

Which will initialise your books class variable, and pull all your books out of the database so you can use them.

Now to see your books, you can pull them into your index.html.erb view

Step 7: In welcome/index.html.erb enter something like
<% @books.each do |book| %>

<%= book.title %>

<%= book.description %>

Author: <%= book.author %>

<% end %>

If you refresh your browser (make sure you have saved all files and turned the server on with $rails server) – you should see your books listed!

Now we learnt a whole lot of other stuff about routes and things after this – but I think this is enough to get my head around for now.

Leave a reply

Demystifying Rails – Routes, Views, Controllers

Ruby on Rails First App

In our General Assembly course we spent the first 4 weeks learning about the Ruby language, and now we are spending the next 6 weeks building in Ruby on Rails. I have previous experience practicing with rails – from Treehouse, RailsGirls and other tutorials – but I quickly learned that those tutorials weren’t that helpful for helping me understand Rails. For example, all those previous tutorials used ‘scaffolding’ which is a whole lot of Ruby magic and shortcuts, and you don’t really get to understand what is happening. This is bad because then later on if you want to customise it, you don’t know how.

At our General Assembly course, we are learning the how behind Ruby on Rails, going through every little process to better understand it and demystify it. I know I will need to refer back to my notes in the future – so I am putting them here for my own sake:

Create a New Rails App – First Route, Controller and View

To create a new rails app, you simply need to type into the terminal

$ rails new appname

Where appname is obviously whatever the appname is. For this example,  I will say I am making a books app, and so the command would be

Step 1:    $ rails new books_app

It became clear to us later on that we shouldn’t name our app just ‘books’. Because Rails will then make a model called ‘books’ as the default model, and if we didn’t want to use that model, then we would be in a bit of trouble – therefore it is better to name your app something like books_app.

When you run rails new books_app, rails will generate a whole lot of files and folders for you – move into the folder you just created, to view those files

Step 2: $ cd books_app

You should see a whole lot of files, including gem files, db, app, config and more. I like to open this whole folder up in sublime text. Already you have made the basis of your app, and you can view it in your browser by starting up the rails server

Step 3: $ rails server

Note that to get out of rails server, you can do ctrl + c But if you only want to get out of it so that you can use the command line again, you should probably just open a new terminal window.

Step 4: In your browser, go to http://localhost:3000/ which is the port your Rails app will be responding through.

You should get a page saying “Welcome Aboard, You’re Riding Ruby on Rails!” Then, it will have a few tips on the steps to make your app, but the order is a bit different to what we did in our class. First, we made a route to our index page, so that that Welcome page is gone.

Step 5: Open your Config/routes file and create a new line under the first (existing) line saying

root 'welcome#index'

What this will do is, when someone goes to the root URL,  they will get sent to the Welcome controller’s, Index action. So, this means it will go to the controllers file called WelcomeController (which will have a class called WelcomeController), and then it will use the Index action in that WelcomeController class.

If you save your files and go back to your browser and refresh, you should see an error message saying uninitialized constant WelcomeController – because you haven’t made it yet!

Step 6: Go to app/controllers and make a new file called welcome_controller.rb

In your WelcomeController you want to make a class called WelcomeController, and give it at least one method called index. So it would be like this

class WelcomeController < ApplicationController

def index

end

end
Here you can see that the WelcomeController is inheriting from something called ApplicationController – which is a part of Ruby on Rails, and it has to do this  - it inherits some Rails magic from here too, you see.

Now, if you refresh your template again, you will see another error – this time saying you have a missing template. That’s right – you have the controller in place, but you don’t have anything to view it with – so you need to make a view (or you might call it a template).

As an aside – I love how Rails will tell you what is missing with such great messages, so you can easily (well not easily really) step through the process.

Step 7: Go to app/views and make a new folder called welcome

That’s right, a folder, not a file, because you might want to put a number of different view template files in this folder for the one controller. The naming of the folder to match the controller is also really important – because the Rails magic depends on you using a certain naming style, so it knows where to look

Step 8: In app/views/welcome create a new file called index.html.erb

This file name extension shows that in this file you can write both html and erb (I think it stands for Embedded RuBy) – so you can use html to make the page look however you like, and you can use Ruby to pull things in dynamically.

Write something in that file – for example some html like

<h1>Hola Ruby</h1>

And if you have saved everything, then you should be able to go back into your browser, hit refresh, and see what you wrote!!

 

I think that’s enough for this post. Like we did in class, I will separate out Models as a separate post.

 

 

Leave a reply

The Lovely Ruby Community

When I first started looking at learning to code – using Lynda and Codecademy – I was trying out a bunch of different languages and seeing which ones looked interesting. I found Ruby to be the most beautiful (or English-like, which to me was beautiful), and I read so much buzz about it online, that I thought it might be the language for me to focus on.

This was further confirmed when I attended Rails Girls Brisbane, and I discovered that the Ruby community was full of lovely, helpful people. I was sad to have to come back to Sydney and leave all those lovely mentors behind (including Nigel Rausch who was super helpful), and I was worried that all the nice Ruby people lived in Brisbane.

Well, I was wrong. The other week I went to my first RORO Sydney event (monthly Ruby on Rails event), and discovered that the Sydney Rails crowd is just as friendly. The event was packed, because the special speaker was Yehuda Katz (core developer on Ember, Ruby on Rails and jQuery), so it was a great night to introduce myself to the group.

When I arrived I knew no one there except my General Assembly Tutor, Ben Askins, who immediately introduced me to some people he was sitting with, and then I also introduced myself to some other people. It was the easiest ‘meeting of strangers’ I have ever experienced.

The attendees were welcoming, they introduced me to their friends, they asked me questions about myself, and – different to every single ‘professional event’ I have ever been to before in my life – they did not spend a lot of time talking themselves up, and they weren’t aggressive. They didn’t seem to care that I was fresh and new, and therefore had no interesting information to impart, nor any useful connections to share. It was just so refreshing. A friendly community of smart people who welcome new members and are keen to help them learn and develop. I am still shocked two weeks later.

I am immensely excited to keep learning more Ruby and more about the Ruby Community.

 

Leave a reply

Git Terminology

Git Version Control

I continue to have a hatred of Git and GitHub purely due to my own ignorance and lack of comprehension. Let’s try to overcome this prejudice with a bit of education!

  • master - the repository’s main branch. Depending on the work flow it is the one people work on or the one where the integration happens
  • clone - copies an existing git repository, normally from some remote location to your local environment.
  • commit - submitting files to the repository (the local one); in other VCS it is often referred to as “checkin”
  • fetch or pull - is like “update” or “get latest” in other VCS. The difference between fetch and pull is that pull combines both, fetching the latest code from a remote repo as well as performs the merging.
  • push - is used to submit the code to a remote repository
  • remote - these are “remote” locations of your repository, normally on some central server.
  • SHA - every commit or node in the Git tree is identified by a unique SHA key. You can use them in various commands in order to manipulate a specific node.
  • head - is a reference to the node to which our working space of the repository currently points.
  • branch - is just like in other VCS with the difference that a branch in Git is actually nothing more special than a particular label on a given node. It is not a physical copy of the files as in other popular VCS.

Courtesy of this article here

Also – someone told me that…

Branch is like “Save As”

…which might be helpful to remember

And finally, here is yet another ‘beginners guide’ to Git 

3 Replies

Starting at General Assembly

General Assembly, Learning to codeLast night I had my first class at General Assembly Sydney. The 10 week course started last week, but I was in Shanghai, so missed the first 2 lessons. Yesterday, the teacher Ben allowed me to come to class 2 hours early to try and catch up a bit.

He took me through how the classes will run and use Git (nightmare!), and got me started on my homework. He also offered to help me again today – so, my first impressions of the course are excellent – very supportive.

The other thing I like about the course is that all the materials are being used through GitHub. This means I HAVE to learn how to use it, and hopefully by the end of the 10 weeks I will be comfortable with it.

There are 7 people in my class, so we have a good teacher/pupil ratio, and the classes are 3 hours on Monday and Wednesday night (agggh Masterchef!).

So, the first two lessons last week were about the basics of the terminal, how to use Git and then an introduction to Ruby. My first class was about Ruby conditionals, arrays and hashes. Up until hashes I think I was semi-fine…then I hit hashes, and my brain fell to pieces. I hope it was just because it was the end of a long day. In any case, the teacher sent us a follow up message after the class saying it’s cool if we were a bit confused, not to hate on ourselves, and that we’ll go over it a bit more on Wednesday. I suspect this message was almost completely for me.

I’m looking forward to tomorrow nights class, not only to get a better handle on hashes, but also because afterwards I am going to head straight down to the casino for this weeks Messina special – salted caramel and chocolate gelato.

Leave a reply