Language/RubyOnRails
rails controller
uuukpyo
2020. 1. 9. 13:01
728x90
1. respond_to
형식에 따라 다른 템플릿을 출력해주는 메소드
여러가지 템플릿(HTML, JSON, XML 등등) 의 형식으로 출력이 가능하다.
2. redirect_to
어딘가로 이동한다는 뜻
밑의 예시에서는 post가 save에 성공하면 게시물로 이동하게 된다.
3. flash
flash[:notice], flash[:alert] 등으로 성공했을때와 실패했을때 메세지를 띄워줄수있다.
독자적인 notice, alert 등의 이름으로도 사용할 수 있다.
flash[:아무 이름] = "넣고 싶은 메시지" 형식으로 사용도 가능
def new
respond_to do |format|
if @post.save
format.html {redirect_to @post, notice: '저장이 성공적으로 되었습니다.'}
format.json {render :show, status: :created, location: @post }
else
format.html {render :new}
format.json {render json: @post.errors, status: :unprocessable_entity}
end
end
end
4. strong parameter
지정된 속성만을 변경할 수 있다.
예시에서는 post 작성자가 title, content 속성만 변경이 가능!
안전하게 params를 받아올 수 있다.
params.require(모델 이름).permit(:속성1, :속성2)
def post_params
params.require(:post).permit(:title, :content)
end
728x90