서버 간의 트래픽을 보호하기 위해 Iptables 방화벽을 설정하는 방법

소개

애플리케이션 설정의 개별 구성 요소를 다른 노드에 배포하는 것은 로드를 줄이고 수평 확장을 시작하는 일반적인 방법입니다. 일반적인 예는 애플리케이션과 별도의 서버에 데이터베이스를 구성하는 것입니다.

더 많은 것을 읽으십시오 →

Nmap 및 Tcpdump로 방화벽 구성을 테스트하는 방법

소개

인프라에 방화벽을 설정하는 것은 서비스에 대한 보안을 제공하는 좋은 방법입니다. 만족스러운 정책을 개발했으면 다음 단계는 방화벽 규칙을 테스트하는 것입니다. 방화벽 규칙이 수행하고 있다고 생각하는 대

더 많은 것을 읽으십시오 →

일반적인 LetsEncrypt 오류를 수정하는 방법

소개

도메인 이름 또는 HTTPS 지원을 구성할 때 발생할 수 있는 일반적인 오류가 많이 있습니다. 도메인 이름 시스템인 DNS는 문제를 해결하기 어려울 수 있으며 오류가 스택의 다른 부분으로 인해 발생할 수 있는 경우 오

더 많은 것을 읽으십시오 →

jq로 JSON 데이터를 변환하는 방법

\u003cem\u003e저자는 Write for DOnations 프로그램을 선택했습니다.\u003c/em\u003e

소개

큰 JSON 파일로 작업할 때 필요한 정보를 찾고 조작하기 어려울 수 있습니다. 모든 관련 스니펫을 복사하여 붙여넣어 총계를 수동으로 계

더 많은 것을 읽으십시오 →

Go에서 패키지 가져오기

소개

다양한 프로젝트에서 코드를 빌리고 공유할 수 있는 기능은 널리 사용되는 프로그래밍 언어와 전체 오픈 소스 커뮤니티의 기초입니다. 코드를 차용하면 프로그래머는 자신의 필요에 맞는 코드를 작성하는 데 대부

더 많은 것을 읽으십시오 →

SQL에서 기본 키를 사용하는 방법

\u003cem\u003e저자는 Write for DOnations 프로그램을 선택했습니다.\u003c/em\u003e

소개

관계형 데이터베이스의 테이블에서 개별 행에 대한 식별자 역할을 하는 \u003cem\u003e기본 키\u003c/em\u003e의 중요한 특성 중 하나입니다.

<

더 많은 것을 읽으십시오 →

Ubuntu 22.04에서 Ruby on Rails 애플리케이션을 구축하는 방법

개발 서버에서 작업하는 경우 먼저 \u003ccode\u003e3000\u003c/code\u003e 포트에서 연결이 허용되는지 확인하십시오.

  1. sudo ufw allow 3000

그런 다음 \u003ccode\u003e--binding\u003c/code\u003e 플래그로 서버를 시작하여 서버 IP 주소에 바인딩합니다.

  1. rails server --binding=your_server_ip

브라우저에서 \u003ccode\u003ehttp://\u003cmark\u003eyour_server_ip\u003c/mark\u003e:3000\u003c/code\u003e으로 이동하여 기본 Rails 랜딩 페이지에 액세스합니다.

준비가 되면 터미널에서 \u003ccode\u003eCTRL+C\u003c/code\u003e를 눌러 서버를 중지할 수 있습니다.

애플리케이션이 생성되고 배치되면 고유한 애플리케이션을 생성하기 위해 Rails 상용구에서 구축을 시작할 준비가 된 것입니다.

3단계 - 애플리케이션 스캐폴딩

상어 응용 프로그램을 만들려면 응용 프로그램 데이터를 관리하기 위한 \u003cem\u003e모델\u003c/em\u003e, 해당 데이터와 사용자 상호 작용을 가능하게 하는 \u003cem\u003e보기\u003c/em\u003e 및 \u003cem\u003e컨트롤러\u003c/em\u003e를 만들어야 합니다. \u003e 모델과 뷰 간의 통신을 관리합니다. 이를 빌드하려면 \u003ccode\u003erails generate scaffold\u003c/code\u003e 명령을 사용하세요. 이렇게 하면 애플리케이션에 대한 모델, CRUD(Create, Read, Update, and Delete) 작업, 그리고 부분, 헬퍼 및 테스트에 대한 템플릿이 생성됩니다.

\u003ccode\u003egenerate scaffold\u003c/code\u003e 명령은 내부적으로 많은 작업을 수행합니다. 명령에는 모델 이름과 데이터베이스 테이블에서 원하는 필드가 포함됩니다. Rails는 Ruby 클래스를 사용하는 동시에 \u003ccode\u003eActiveRecord::Base\u003c/code\u003e 클래스도 상속합니다. 이는 Ruby 클래스로 작업하는 것과 동일한 방식으로 모델 클래스로 작업할 수 있음을 의미합니다. 또한 Active Record에서 메서드를 가져올 수도 있습니다. Active Record는 각 클래스가 데이터베이스의 테이블에 매핑되고 해당 클래스의 각 인스턴스가 해당 테이블의 행에 매핑되도록 합니다.

다음 명령을 실행하여 \u003ccode\u003eShark\u003c/code\u003e 모델, 컨트롤러 및 관련 보기를 생성합니다.

  1. rails generate scaffold Shark name:string facts:text

이 명령의 \u003ccode\u003ename:string\u003c/code\u003e 및 \u003ccode\u003efacts:text\u003c/code\u003e 옵션은 데이터베이스 테이블에서 만들고 있는 필드와 수락해야 하는 데이터 유형을 나타냅니다. 둘 다 원하는 것을 입력할 수 있는 공간을 제공합니다. \u003ccode\u003etext\u003c/code\u003e 옵션은 더 많은 문자를 허용합니다.

이 명령을 입력하면 생성된 모든 다른 파일이 출력에 표시됩니다.

Output
invoke active_record create db/migrate/20190804181822_create_sharks.rb create app/models/shark.rb . . . invoke resource_route route resources :sharks invoke scaffold_controller create app/controllers/sharks_controller.rb invoke erb create app/views/sharks create app/views/sharks/index.html.erb create app/views/sharks/edit.html.erb create app/views/sharks/show.html.erb create app/views/sharks/new.html.erb create app/views/sharks/_form.html.erb . . .

Rails는 \u003ccode\u003eapp/models/shark.rb\u003c/code\u003e에서 모델을 생성했고 이에 따라 데이터베이스 마이그레이션을 수행했습니다. . 마이그레이션 파일의 타임스탬프는 예제 출력과 다릅니다.

또한 \u003ccode\u003eapp/controllers/sharks_controller.rb\u003c/code\u003e 컨트롤러와 \u003ccode\u003eapp/views/sharks\u003c/code\u003e에 수집된 애플리케이션의 CRUD 작업과 관련된 뷰를 생성했습니다. 이러한 보기 중에는 여러 보기에서 사용되는 코드를 포함하는 부분인 \u003ccode\u003e_form.html.erb\u003c/code\u003e가 있습니다.

마지막으로 Rails는 \u003ccode\u003econfig/routes.rb\u003c/code\u003e에 리소스가 풍부한 새 경로인 \u003ccode\u003eresources :sharks\u003c/code\u003e를 추가했습니다. 이렇게 하면 Rails 라우터가 들어오는 HTTP 요청을 \u003ccode\u003esharks\u003c/code\u003e 컨트롤러 및 관련 보기와 일치시킬 수 있습니다.

Rails가 애플리케이션 코드를 구축하는 많은 작업을 수행했지만 어떤 일이 일어나고 있는지 더 잘 이해하기 위해 일부 파일을 살펴볼 가치가 있습니다.

컨트롤러 파일을 이해하려면 터미널에 다음 명령을 입력하십시오.

  1. cat app/controllers/sharks_controller.rb
Output
class SharksController < ApplicationController before_action :set_shark, only: %i[ show edit update destroy ] # GET /sharks or /sharks.json def index @sharks = Shark.all end # GET /sharks/1 or /sharks/1.json def show end # GET /sharks/new def new @shark = Shark.new end # GET /sharks/1/edit def edit end # POST /sharks or /sharks.json def create @shark = Shark.new(shark_params) respond_to do |format| if @shark.save format.html { redirect_to shark_url(@shark), notice: "Shark was successfully created." } format.json { render :show, status: :created, location: @shark } else format.html { render :new, status: :unprocessable_entity } format.json { render json: @shark.errors, status: :unprocessable_entity } end end end # PATCH/PUT /sharks/1 or /sharks/1.json def update respond_to do |format| if @shark.update(shark_params) format.html { redirect_to shark_url(@shark), notice: "Shark was successfully updated." } format.json { render :show, status: :ok, location: @shark } else format.html { render :edit, status: :unprocessable_entity } format.json { render json: @shark.errors, status: :unprocessable_entity } end end end # DELETE /sharks/1 or /sharks/1.json def destroy @shark.destroy respond_to do |format| format.html { redirect_to sharks_url, notice: "Shark was successfully destroyed." } format.json { head :no_content } end end private # Use callbacks to share common setup or constraints between actions. def set_shark @shark = Shark.find(params[:id]) end # Only allow a list of trusted parameters through. def shark_params params.require(:shark).permit(:name, :facts) end end

컨트롤러는 정보를 가져오고 관련 모델로 전달하는 방법과 특정 보기와 연결하는 방법을 관리합니다. 예를 들어 \u003ccode\u003esharks\u003c/code\u003e 컨트롤러에는 표준 CRUD 작업에 대략적으로 매핑되는 일련의 메서드가 포함되어 있습니다. 오류 발생 시 효율성을 높이기 위해 CRUD 함수보다 더 많은 방법이 있습니다.

예를 들어, \u003ccode\u003ecreate\u003c/code\u003e 메소드를 고려하십시오.

. . .
  def create
    @shark = Shark.new(shark_params)

    respond_to do |format|
      if @shark.save
        format.html { redirect_to @shark, notice: 'Shark was successfully created.' }
        format.json { render :show, status: :created, location: @shark }
      else
        format.html { render :new }
        format.json { render json: @shark.errors, status: :unprocessable_entity }
      end
    end
  end
. . . 

\u003ccode\u003eShark\u003c/code\u003e 클래스의 새 인스턴스가 성공적으로 저장되면 \u003ccode\u003eredirect_to\u003c/code\u003e는 컨트롤러로 전달되는 새 요청을 생성합니다. 이것은 \u003ccode\u003eGET\u003c/code\u003e 요청이며 최근에 추가한 입력을 사용자에게 표시하는 \u003ccode\u003eshow\u003c/code\u003e 메서드에 의해 처리됩니다.

오류가 발생하면 Rails는 라우터에 다른 요청을 하는 대신 \u003ccode\u003eapp/views/sharks/new.html.erb\u003c/code\u003e 템플릿을 다시 렌더링하여 사용자가 데이터를 제출할 수 있는 또 다른 기회를 제공합니다.

\u003ccode\u003esharks\u003c/code\u003e 컨트롤러 외에도 Rails는 컨트롤러의 \u003ccode\u003eindex\u003c/code\u003e 메서드에 매핑되는 \u003ccode\u003eindex\u003c/code\u003e 보기용 템플릿을 만들었습니다. 이것을 응용 프로그램의 루트 보기로 사용합니다.

다음 명령을 실행하여 파일을 출력합니다.

  1. cat app/views/sharks/index.html.erb
Output
<p style="color: green"><%= notice %></p> <h1>Sharks</h1> <div id="sharks"> <% @sharks.each do |shark| %> <%= render shark %> <p> <%= link_to "Show this shark", shark %> </p> <% end %> </div> <%= link_to "New shark", new_shark_path %>

\u003ccode\u003eindex\u003c/code\u003e 보기는 데이터베이스의 \u003ccode\u003esharks\u003c/code\u003e 테이블에 매핑되는 \u003ccode\u003eShark\u003c/code\u003e 클래스의 인스턴스를 순환합니다. ERB 템플릿을 사용하여 보기는 개별 상어 인스턴스와 연결된 테이블의 각 필드(\u003ccode\u003ename\u003c/code\u003e 및 \u003ccode\u003efacts\u003c/code\u003e)를 출력합니다.

그런 다음 뷰는 \u003ccode\u003erails generate scaffold\u003c/code\u003e 명령으로 \u003ccode\u003esharks\u003c/code\u003e 자원 경로를 정의할 때 사용할 수 있게 된 헬퍼를 사용합니다.

\u003ccode\u003enew\u003c/code\u003e 보기는 부분이라고 하는 것을 사용합니다. 다음을 실행하여 \u003ccode\u003eapp/views/sharks/new.html.erb\u003c/code\u003e 템플릿을 반환합니다.

  1. cat app/views/sharks/new.html.erb
Output
<h1>New shark</h1> <%= render "form", shark: @shark %> <br> <div> <%= link_to "Back to sharks", sharks_path %> </div>

이 템플릿은 새 상어 항목에 대한 입력 필드가 없는 것처럼 보일 수 있지만 \u003ccode\u003e렌더링 양식\u003c/code\u003e에 대한 참조는 템플릿이 \u003ccode\u003e_form.html.erb\u003c/code\u003e 부분을 가져오고 있음을 나타냅니다. 뷰에서 반복되는 코드를 추출합니다.

\u003ccode\u003e_form.html.erb\u003c/code\u003e 파일을 출력하여 새 상어 인스턴스가 생성되는 방법을 더 잘 이해할 수 있습니다.

  1. cat app/views/sharks/_form.html.erb
Output
<%= form_with(model: shark) do |form| %> <% if shark.errors.any? %> <div style="color: red"> <h2><%= pluralize(shark.errors.count, "error") %> prohibited this shark from being saved:</h2> <ul> <% shark.errors.each do |error| %> <li><%= error.full_message %></li> <% end %> </ul> </div> <% end %> <div> <%= form.label :name, style: "display: block" %> <%= form.text_field :name %> </div> <div> <%= form.label :facts, style: "display: block" %> <%= form.text_area :facts %> </div> <div> <%= form.submit %> </div> <% end %>

이 템플릿은 양식 도우미를 사용합니다. 양식 도우미는 특정 모델의 필드와 범위를 사용하여 사용자 입력에서 새 개체를 쉽게 만들 수 있도록 설계되었습니다. 이 예에서 \u003ccode\u003eform_with\u003c/code\u003e는 \u003ccode\u003emodel: shark\u003c/code\u003e를 인수로 사용하고 생성되는 새 양식 작성기 개체에는 \u003ccode\u003esharks의 필드에 해당하는 필드 입력이 있습니다. 테이블. 이는 사용자가 상어 \u003ccode\u003e이름\u003c/code\u003e과 상어 \u003ccode\u003e사실\u003c/code\u003e을 모두 입력할 수 있는 양식 필드가 있음을 의미합니다.

이 양식을 제출하면 애플리케이션의 나머지 부분이 params 메소드를 통해 액세스할 수 있는 사용자 데이터가 포함된 JSON 응답이 생성됩니다. 이렇게 하면 해당 데이터로 \u003ccode\u003eActionController::Parameters\u003c/code\u003e 객체가 생성됩니다.

이제 \u003ccode\u003erails generate scaffold\u003c/code\u003e가 무엇을 생성했는지 알았으므로 애플리케이션의 루트 보기 설정으로 이동할 수 있습니다.

4단계 - 애플리케이션 루트 뷰 생성 및 기능 테스트

이상적으로는 사용자가 애플리케이션의 목적을 즉시 파악할 수 있도록 애플리케이션의 랜딩 페이지가 애플리케이션의 루트에 매핑되기를 원합니다.

예를 들어 \u003ccode\u003eWelcome\u003c/code\u003e 컨트롤러와 관련 \u003ccode\u003eindex\u003c/code\u003e 뷰를 생성하여 사용자에게 애플리케이션의 다른 부분으로 연결될 수 있는 일반 랜딩 페이지를 제공할 수 있습니다.

이를 설정하려면 \u003ccode\u003econfig/routes.rb\u003c/code\u003e에서 라우팅 설정을 수정하여 애플리케이션의 루트를 지정해야 합니다.

\u003ccode\u003enano\u003c/code\u003e 또는 좋아하는 편집기를 사용하여 편집할 \u003ccode\u003econfig/routes.rb\u003c/code\u003e를 엽니다.

  1. nano config/routes.rb
Rails.application.routes.draw do
  resources :sharks
  # Define your application routes per the DSL in https://guides.rubyonrails.org/routing.html

  # Defines the root path route ("/")
  # root "articles#index"
end

더 구체적으로 설정하지 않으면 \u003ccode\u003ehttp://localhost:3000\u003c/code\u003e 또는 \u003ccode\u003ehttp://\u003cmark\u003eyour_server_ip\u003c/mark\u003e:3000\u003c/code\u003e의 기본 보기가 기본값이 됩니다. 레일스 환영 페이지.

응용 프로그램의 루트 뷰를 sharks 컨트롤러의 \u003ccode\u003eindex\u003c/code\u003e 뷰에 매핑하려면 \u003ccode\u003e#\u003c /code> 및 articleshark로 교체:

Rails.application.routes.draw do
  resources :sharks

  root 'sharks#index' 
  # For details on the DSL available within this file, see http://guides.rubyonrails.org/routing.html
end

파일을 저장하고 편집이 끝나면 편집기를 종료하십시오. \u003ccode\u003enano\u003c/code\u003e를 사용하여 파일을 종료한 경우 \u003ccode\u003eCTRL+X\u003c/code\u003e, \u003ccode\u003eY\u003c/code\u003e를 누른 다음 \u003ccode\u003eENTER\u003c/code\u003e를 누르십시오.

이제 사용자가 애플리케이션 루트로 이동할 때 기본 Rails 랜딩 페이지가 아닌 상어 랜딩 페이지로 들어갑니다. 또한 이제 새 상어 항목을 만들고 기존 항목을 검토하고 주어진 항목을 편집하거나 삭제할 수 있습니다.

그런 다음 다음 명령을 사용하여 마이그레이션을 실행합니다.

  1. rails db:migrate

이 출력은 마이그레이션을 확인합니다.

Output
== 20230124215633 CreateSharks: migrating ===================================== -- create_table(:sharks) -> 0.0041s == 20230124215633 CreateSharks: migrated (0.0045s) ============================

Rails 서버를 다시 시작하십시오. 로컬에서 작업하는 경우 다음을 실행합니다.

  1. rails s

개발 서버에서 다음을 실행합니다.

  1. rails s --binding=your_server_ip

로컬에서 작업 중인 경우 \u003ccode\u003elocalhost:3000\u003c/code\u003e으로 이동하고 개발 서버에서 작업 중인 경우 \u003ccode\u003ehttp://\u003cmark\u003eyour_server_ip\u003c/mark\u003e:3000\u003c/code\u003e로 이동하여 새 방문 페이지에 액세스:

소개

루비. 공통 목표가 있는 개발자에게 집합 규칙이 가장 적합하다고 가정하여 응용 프로그램 개발에 대한 독단적인 접근 방식을 취합니다. 따라서 Rails는 대부분의 웹 애플리케이션에 필요한 기본 기능을 제공하기

더 많은 것을 읽으십시오 →

첫 루비 프로그램을 작성하는 방법

소개

\Hello, World! 프로그램은 컴퓨터 프로그래밍의 고전적이고 유서 깊은 전통입니다.초보자를 위한 작고 완전한 첫 번째 프로그램이며 환경이 올바르게 구성되었는지 확인하는 좋은 방법입니다.

이 튜토리얼은 Ruby

더 많은 것을 읽으십시오 →

Windows 10에서 Ruby를 설치하고 로컬 프로그래밍 환경을 설정하는 방법

소개

Ruby는 간단한 스크립트에서 게임 및 웹 애플리케이션에 이르기까지 무엇이든 작성하는 데 사용할 수 있는 동적 프로그래밍 언어입니다. 1993년 일본에서 처음 출시됐으나 2005년 서버사이드 웹 개발용 언어로 인기를

더 많은 것을 읽으십시오 →

Ubuntu 22.04에서 Ruby를 설치하고 로컬 프로그래밍 환경을 설정하는 방법

소개

Ruby는 간단한 스크립트에서 게임 및 웹 애플리케이션에 이르기까지 무엇이든 작성하는 데 사용할 수 있는 동적 프로그래밍 언어입니다. 1993년 일본에서 처음 출시됐으나 2005년 서버사이드 웹 개발용 언어로 인기를

더 많은 것을 읽으십시오 →