[rails] 스캐폴딩 기능 개발 기초 : 상세 화면 작성

2016. 8. 14. 21:54프로그래밍/Ruby on Rails

728x90
728x90
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
[elkiss@elkiss-centos controllers]$ vim books_controller.rb 
  before_action :set_book, only: [:show, :edit, :update, :destroy]
...
  def show
  end
...
  private
    # Use callbacks to share common setup or constraints between actions.
    def set_book
      @book = Book.find(params[:id])
    end
 
    # Never trust parameters from the scary internet, only allow the white list through.
    def book_params
      params.require(:book).permit(:isbn, :title, :price, :publish, :published, :cd)
    end
end
cs


before_action 메서드는 액션 메서드가 실행되기 전에 실행할 메서드이다.

이러한 메서드를 필터라고 부른다.


1
before_action method, only: action
cs


method는 필터로 실행되는 메서드, action은 필터를 적용할 액션 매서드(어레이)


show 액션이 비어 있는 이유는 필터 메서드에서 처리하는 내용이 전부이므로 메서드 내부에 아무것도 없다.


필터가 하는 일은 private 아래에서 정의한다. 액션으로 호출되지 않기때문에 private으로 선언되는 것이다.


@book = Book.find(params[:id])

parmams 메서드를 통해 :id 매개변수 값을 추출한다. /books/:id(.:format)이라는 URL 패턴과 연결되어 있다.

그래서 books/1과 같은 형태로 show 액션을 호출하는데 여기서 :id 값을 얻을 수 있고 이를 이용해 테이블을 검색하여 레코드를 찾아낸다.


이를 이용해 show.html.erb 템플릿 파일에서 @book 객체를 접근할 수 있다.

728x90
반응형