[Rails] I don't want to get lost anymore. Create new models, tables, controllers and views.

Introduction

This article summarizes what you'll do after launching your Rails app. When creating some kind of function, the work of creating a model, creating a controller, writing routing, etc. often occurs. I forget the syntax every time, so I've put together a series of steps.

Creating a controller

First, create the controller. This time, we will create a function to save images, so let's call it images.

rails g controller images

Creating a model

Let's create an image model with the following command!

rails g model image

You should now have an image model. If necessary, write validations and associations in your model.

Create table

I think the migration file was created when the model was created. Edit this file to set the primary key and null constraint. In my case, "filename" is used as the primary key and null constraint is applied as follows. Since I used it as the primary key, I may not need such restrictions, but ...

class CreateImages < ActiveRecord::Migration[5.2]
  def change
    create_table :images, id: false, primary_key: :filename do |t|
      t.string :filename, null: false
      t.timestamps
    end
  end
end

Now run migrate and if successful, the table will be created!

rails db:migrate

Create view

Let's create index.html.haml because it is a page that displays a list of images. The images directory has been created in the previous work, so create it there. As for the contents of the view, I will not cover it in this article, so I will put out "Hello World" appropriately.

%h1
  HelloWorld

routing

It's almost done when you come here. Describe the routes of images in routes.rb. This time I used the resources method to set only the index action.

Rails.application.routes.draw do
  resources :images, only: [:index]
end

result

it is complete! This will make my job easier ...!

スクリーンショット 2020-08-12 4.25.04.png

Recommended Posts

[Rails] I don't want to get lost anymore. Create new models, tables, controllers and views.
(Ruby on Rails6) How to create models and tables
I want to create a form to select the [Rails] category
I really want to do "new T ()"! (And without inspection exceptions)
[Rails] I want to send data of different models in a form
[Active Admin] I want to customize the default create and update processing
[Rails] I studied the difference between new method, save method, build method and create method.
Let's take advantage of VScode's snippet function ~ I don't want to hit <% =%> anymore ~
I want to recursively get the superclass and interface of a certain class
[Rails] rails new to create a database with PostgreSQL
I want to play with Firestore from Rails
[Rails] How to get success and error messages
[Rails] Difference between create method and new + save method
[Rails] I want to load CSS with webpacker
I want to get the value in Ruby