Web Backend/Ruby on Rails

루비온레일즈에서 데이터베이스 다루기 (feat.Windows)

xProgrammer 2022. 5. 29. 13:00

MySQL서버 설치

sudo apt install mysql-server
sudo service mysql start
sudo mysql_secure_installation

mysql_secure_installation

더보기
  • Do you wish to continue with the password provided?(Press y|Y for Yes, any other key for No) : Y
    By default, a MySQL installation has an anonymous user,
    allowing anyone to log into MySQL without having to have
    a user account created for them. This is intended only for
    testing, and to make the installation go a bit smoother.
    You should remove them before moving into a production
    environment.

    Remove anonymous users? (Press y|Y for Yes, any other key for No) : Y
    Success.


    Normally, root should only be allowed to connect from
    'localhost'. This ensures that someone cannot guess at
    the root password from the network.

    Disallow root login remotely? (Press y|Y for Yes, any other key for No) : Y
    Success.

    By default, MySQL comes with a database named 'test' that
    anyone can access. This is also intended only for testing,
    and should be removed before moving into a production
    environment.


    Remove test database and access to it? (Press y|Y for Yes, any other key for No) : Y
     - Dropping test database...
    Success.

     - Removing privileges on test database...
    Success.

    Reloading the privilege tables will ensure that all changes
    made so far will take effect immediately.

    Reload privilege tables now? (Press y|Y for Yes, any other key for No) : Y
    Success.

    All done! 

MySQL에서 사용할 사용자생성

$ mysql -u root -p
mysql > create user '[아이디]'@'%' identified by '[비밀번호]';
mysql > grant all privileges on [데이터베이스이름].* to '[아이디]'@'%' with grant option;

프로젝트생성

rails new [프로젝트이름] -d mysql
bundle exec rake db:create

모델만들기

bundle exec rails g model post

생성된파일

app/models/post.rb: 실제 테이블과 연결되는 Model
db/migrate/년월일시분초_create_posts.rb: 테이블을 생성하기 위한 migratoin 파일
test/fixtures/posts.yml: 테스트를 위한 Dummy 데이터
test/models/post_test.rb: Model의 유닛 테스트를 위한 파일

테이블설계
db/migrate/년월일시분초_create_posts.rb 파일 수정

class CreatePosts < ActiveRecord::Migration[7.0]
  def change
    create_table :posts do |t|
      t.string :title
      t.text :content
      t.timestamps
    end
  end
end

테이블생성

bundle exec rake db:migrate

생성된파일

db/schema.rb

데이터입력 (Create) > 컨트롤러: app/controllers/home_controller.rb

class HomeController < ApplicationController
    def index
    end

    # 데이터입력폼
    def form

    end
    # 데이터입력처리
    def create
        post = Post.new
        post.title = params[:title]
        post.content = params[:content]
        post.save

        redirect_to '/list.html'
    end
end

데이터입력 (Create) > 뷰: app/views/home/form.erb

<a href="/list">Go back</a><br/>
<form action="/create" method="POST">
  <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>" />
  <label for="title">title:</label>
  <input type="text" name="title" />
  <label for="content">content:</label>
  <input type="text" name="content" />
  <input type="submit" />
</form>

데이터입력 (Create) > 라우팅: config/routes.rb

Rails.application.routes.draw do
  ...
  get '/form', to: 'home#form'
  post '/create', to: 'home#create'
end

데이터읽기 (Read) > 컨트롤러: app/controllers/home_controller.rb

class HomeController < ApplicationController
    ...
    def list
        @posts = Post.all
    end
end

데이터읽기 (Read) > 뷰: app/views/home/list.erb

<style>
table, th, td {
  border: 1px solid black;
}
</style>
<a href="/form">Create New Post</a>
<table>
    <thead>
        <tr>
            <th>Title</th>
            <th>Content</th>
            <th>Action</th>
        </tr>
    </thead>
    <tbody>
        <% @posts.each do |post| %>
        <tr>
            <td><%= post.title %></td>
            <td><%= post.content %></td>
            <td>
            	<a href="/modify/<%= post.id %>">modify</a><br/>
            	<a href="/delete/<%= post.id %>">delete</a><br/>
            </td>
        </tr>
        <% end %>
    </tbody>
</table>

데이터읽기 (Read) > 라우팅: config/routes.rb

Rails.application.routes.draw do
  ...
  get '/list', to: 'home#list'
end

데이터수정 (Update) > 컨트롤러: app/controllers/home_controller.rb

class HomeController < ApplicationController
    ...
    #업데이트화면
    def modify
        @post = Post.find(params[:id])
    end
    # 업데이트처리
    def update
        post = Post.find(params[:id])
        post.title = params[:title]
        post.content = params[:content]
        post.save

        redirect_to '/list.html'
    end
end

데이터수정 (Update) > 뷰: app/views/modify.rb

<a href="/list">Go back</a><br/>
<form action="/update/<%= @post.id %>" method="POST">
  <input type="hidden" name="authenticity_token" value="<%= form_authenticity_token %>" />
  <label for="title">title:</label>
  <input type="text" name="title" value="<%= @post.title %>"/>
  <label for="content">content:</label>
  <input type="text" name="content" value="<%= @post.content %>" />
  <input type="submit" />
</form>

데이터수정 (Update) > 라우팅: config/routes.rb

 Rails.application.routes.draw do
  ...
  get '/modify/:id', to: 'home#modify'
  post '/update/:id', to: 'home#update'
  
end

데이터삭제 (Delete) > 컨트롤러: app/controllers/home_controller.rb

class HomeController < ApplicationController
    ...
    def delete
        Post.destroy(params[:id])

        redirect_to '/list'
    end
end

데이터삭제 (Delete) > 라우팅: config/routes.rb

Rails.application.routes.draw do
  ...
  get '/delete/:id', to: 'home#delete'
end

 

 

참고사이트