모바일 식권 서비스 만들기(6) - scaffold 를 이용한 모델, crud 기능 만들기 (Building a Mobile coupon for meal - Building model and crud function by using scaffold)
모바일 식권 서비스 만들기(6) - scaffold 를 이용한 모델, crud 기능 만들기 (Building a Mobile coupon for meal - Building model and crud function by using scaffold)
이번엔 scaffold 라는 rails 의 훌륭한 기능을 이용해 model과 crud 기능을 만들어보려고 한다. 여기서 model이란 DB의 table 개념이고 crud 는 create, read, update, destroy(or delete) 기능을 말하는 것이다. 하나의 model 그리고 crud 의 기능을 구현하면 하나의 게시판을 만들 수 있기 때문에 매우 기본적이면서도 가장 중요하다고 볼 수 있다. 그런데 rails 에서 이것을 아주 간단하게(1줄~2줄로!) 만들 수 있다.
이제 방법을 아래에서 살펴보자.
How to use scaffold for building model and crud function
- 먼저 현재 디렉토리(폴더)가 어딘지 확인하고 작업하고 있는 프로젝트 디렉토리에 들어간다. 만약 현재 프로젝트 디렉토리에 있다면 할 필요 없음 !
cd projectName
- 그 다음 scaffold 를 만드는 명령어를 쓴다. rails g scaffold 모델명(컨트롤러명) 모델의 속성이름:속성타입 식이다.
rails g scaffold Menu restaurant_name:string corner:string meal_time:string food_img:string main_menu:string menu1:string menu2:string menu3:string menu4:string menu5:string menu6:string menu7:string meal_date:date description:text stop:string user:references
맨 마지막에 user:references 는 기존에 만들어져있는 user 모델과 연결하는 작업인데 User 모델이 1, Menu model에 N이 되는 관계다. 쉽게 말하자면 ‘1명’(user)의 사용자가 '여러개 게시글(menu)'을 쓸 수 있는 게시판을 만드는 모델 관계를 만들어주는 것이다. 이해가 안간다면 내가 설명이 이상한거니 굳이 여기서 이해를 안해도 된다.
아무튼 user:references 를 한다면 model 폴더에 menu.rb 파일에 belongs_to :user 라는 연결고리가 저절로 생긴다. 그리고
menu 모델에 user_id 속성이 생기고, index user_id 가 생긴다.
아무튼 이건 뭐 별로 중요한건 아니니 ! 다음으로 !
3. 그리고 rake db:migrate 를 하면 끝 !
rake db:migrate
그리고 기본 url 뒤에 /menus 를 붙여서 들어가면
이런 화면이 나올 것이다. 그러면 menu 라는 게시판이 만들어졌다 ! new menu 에 들어가면 글을 쓸 수 있고 쓴 글을 보거나 지우거나 수정하거나 할 수 있게 된 것이다. 단 2줄만에 !
*추가적으로 1:N 관계를 위해 작업을 해줘야 할 것이 있다.
- Model 폴더에 있는 User.rb 파일에 아래와 같이 has_many :menus 를 작성해준다.
class User < ApplicationRecord
# Include default devise modules. Others available are:
# :confirmable, :lockable, :timeoutable and :omniauthable
devise :database_authenticatable, :registerable,
:recoverable, :rememberable, :trackable, :validatable
has_many :menus
end
- 그리고 menu.rb 파일에 , optional: true 를 붙여 준다. rails 5에서는 이걸 붙여줘야하는 것 같다.
class Menu < ApplicationRecord
belongs_to :user, optional: true
end
이러면 정말 끝 !
댓글
댓글 쓰기