본문 바로가기

Wep Develop/Ruby on Rails

[Ruby on Rails] Scaffold 이용해 게시판+댓글구현


Scaffold = 뼈대 ( migration / model / routes / controller / view를 한 방에! )


rails g scaffold post title:string content:text            # 모델이름 post 컨트롤러이름 posts
rake db:migrate
routes에서 root 'posts#index'

rails g model comment content:string post_id:integer  # 댓글기능추가하기
rails g controller comments create destroy
rake db:migrate

* rake routes 라우트 확인하는 명령어
* rails c




1. 라우트 설정하기



resource : CRUD할수있는 정보 (무엇을)
HTTP method : 추출, 생성, 변경, 제거 (어떻게)

# comments 줄은 직접입력해준 것.
# do end 이용해 post와 comment 두개 아이디 동시에 넘기는 것도 가능



routes이름이 겹치게 생성됨! 같은 posts/:id를 받아 보고 삭제하고 수정하므로!
index 의 link_to 'Show', 'Edit', 'Destroy'를 보면 왜 이런지 이해됨
*이거 되게 중요한 내용임!

* 오른쪽 그림은 찬하님의 강의자료


2. index.html.erb 파헤치기


Show와Destroy 옆의 post는 post_path(post)의 약자.
method가 없으면 get 방식, delete는 매소드가 적혀있음


3. post controller 파헤치기

 

1) edit action
   edit에 왜 아무것도 음슴? => 맨윗줄 before_action :set_post =>기본설정이 되어있음!
2) create action &update action
 respond_to 는 지정된 형식에 따라 다른 템플릿을 출력함
 flash[:아무이름]='넣고싶은메시지' 는 redirect 후로 일시적으로 넣고싶은메시지를 넣을 때 사용한다. 그래서 새로고침하면 사라짐
    flash[:notice] 는 성공적일때 , flash[:alert]는 경고할때 사용한다.
    flash[:notice] flash[:alert] 각각 그냥 notice, alert로 사용할 수 있어서 여기에 사용되었다!
3) post_params action
  그동안 form_for에서 정보를 받았던 방법은
      @post=Post.new
      @post.title=params[:post][:title]
      @post.content=params[:post][:content]
      @post.save
  같은의미라고 보면됨.
4) new action
form_for은 모델과 연동되므로 Post.new가 일단 있어야 사용가능


4. edit.html.erb / new.html.erb 와 _form.html.erb 파헤치기


new와edit에서는같은form 을 쓴다. 따라서, scaffold에서는 form.html을 따로 만들어서 불러온다.
이 때, form_for 은 매우 똑똑해서 상황에 따라 어떻게 불러올것인지를 알아서 다 해줌
( 모델 객체가 신규 or 이미 저장 완료되었는지를 판별하여 적절한 url 또는 html 옵션을 붙여줌)
( :, @post=Post.newcreate 액션으로 @post=Post.find(params[:id])update 액션으로 보내줌 )



1~12줄까지는사용자가정확한정보를입력을안했을때에러메시지


5. 댓글기능 추가해보기

1) routes에 resource를 이용해 only[:create, :destroy]설정해주기


2) show.html
(1) 댓글쓰기폼
form_for Comment.new, url:comments_path
       어떤 행인지 나타내는  Comment.new
       rake routes에서 comments_path를 알아냄
f.hidden_field 의 post_id는 사용자가 입력하는 정보가 아니라,저절로 입력받아져야 하는 내용이다.
따라서, value에 @post.id를 받아온다!


(2) 댓글 보이기
삭제기능은 scaffold의 코드를 긁어와 수정함!
post가 post_path(post)의 약자였으므로, comment_path(comment)로 수정해줌.

3) comments controller
create액션은 post_params처럼 입력해도 무관
@destroy_comment에서 Post.id.Comments.find.....이런식으로 하지 않는 이유는!
     rake routes에서 그냥 id에 comment의 id가 입력되어있다는 것을 확인할 수 있기 때문임. 각 상황에 따라 잘 확인하기.


4) 모델 관계 설정 1:N