Rails 5 on aws c9
12. Contact 작성 기능 구현
컴퍼
2020. 6. 11. 11:17
데이터베이스애 내용을 저장하고 리스트로 출력하는 방법을 알아보겠다.
이전에는 new.html.erb 에서 form_tag 헬퍼를 이용해 받은 변수들을
contacts_controller의 create 액션 에서 받아 create.htnl.erb view에서 보여줬다.
그 대신에 데이터베이스에 저장하는 코드를 삽입하도록 하자.
contacts_controller.rb
class ContactsController < ApplicationController
def index
end
def new
end
def create
@name = params[:name]
@email = params[:email]
@content = params[:content]
new_contact = Contact.new(name: @name, email: @email, content: @content)
if new_contact.save #저장 결과를 bool값으로 리턴한다
redirect_to "/contacts/index" #세이브가 완료되면 컨텍츠들의 리스트를 보는 뷰로 간다
else
redirect_to "/contacts/new" #세이브가 실패하면 폼으로 다시 돌아간다
end
end
end
값을 채우고 제출을 하면
인덱스로 넘어가는걸 볼 수 있다. (저장이 완료되어서 true 조건 만족)
이제 이 index 화면을 꾸며보자.
contacts_controller.rb
class ContactsController < ApplicationController
def index
@all_contacts = Contact.all #배열 형태로 저장된다
end
def new
end
def create
@name = params[:name]
@email = params[:email]
@content = params[:content]
new_contact = Contact.new(name: @name, email: @email, content: @content)
if new_contact.save #저장 결과를 bool값으로 리턴한다
redirect_to "/contacts/index" #세이브가 완료되면 컨텍츠들의 리스트를 보는 뷰로 간다
else
redirect_to "/contacts/new" #세이브가 실패하면 폼으로 다시 돌아간다
end
end
end
index.html.erb
<h1>All Contacts</h1>
<ul>
<% @all_contacts.each do |contact| %>
<li><%= contact.name %> : <%= contact.content %></li>
<% end %>
</ul>
잘 출력되는걸 볼 수 있다.
새로 하나 더 작성하면
잘 나오는걸 볼 수 있다