If you have a table that will be holding a bunch of articles for a blog, the title of that table is articles. The model name will be the singular, so Article (and it should be capitalized).
Table = plural, lowercase of the model name => articles
Model = singular, first letter capitalized of the table name => Article
Model file name = should be lowercase, singular with .rb at the end => article.rb
Controller name = plural of model file name => articles_controller.rb
Filename should always be snake_case.
Model & class names should be CamelCase.
To generate a table:
rails generate migration create_articles
This creates a table in your alpha-blog > db > migrate folder called (a bunch of numbers)_create_articles.rb. When you open this up you’ll see a table, but you need columns. It has the code:
create_table :articles do |t|To add a column and put the header of “title” on it, we need to add this code:
create_table :articles do |t| t.string :titleYou could also have added a column to hold the article’s text (or description) by doing this code:
create_table :articles do |t| t.string :title t.text :descriptionbut we’ll leave it out and add it later to show what to do in case you need to add a column once a table has been created.
We then need to
rails generate migration add_description_to_articles
def change add_column :articles, :description, :text add_column :articles, :created_at, :datetime add_column :articles, :updated_at, :datetimeWhat this just did was added 3 columns to our table titled “Description”, “Created At”, and “Updated At”.Once this is done, you need to migrate the db again.
Once that is finished, you can go back to schema.rb and see the changes that
So we need to create a model to communicate with the database. That is done under app > models > create new file called article.rb. In that new file, you’ll need to put the code:
class Article < ApplicationRecord
Rails magically creates getters and setters for each of the columns we made earlier in the table once we make this model.
You can check to make sure this worked from
rails console. This gives you direct access to your database. You can use it as a playground to test things out. If you type in
Article.all it will show you if there is a connection. You can then type
Article to see all the attributes. There are a lot of things you can do from here, but they are referenced in the video of section 4, lecture 46 at around 15:30. But a few of the commands are:
article = Article.new
article.title = "This is my first article"
article.description = "This is the description
Another way to do this more succinctly is:
article = Article.new(title: "This is my 2nd article.", description: "This is the 2nd description." and then save.
Article.create(title: "This is my 3rd article.", description: "My 3rd description.") – this one you don’t have to save as the create method automatically saves it. This is probably the most effective method.
To get out of the rails console, just