Docs Menu
Docs Home
/ /

MongoDB 데이터 보기 - Sinatra

1

프로젝트 의 루트 수준에서 app.rb 파일 만듭니다. 다음 내용을 app.rb 파일 에 붙여넣어 필요한 gem과 구성 파일 로드합니다.

require 'sinatra'
require 'mongoid'
Mongoid.load!(File.join(File.dirname(__FILE__), 'config', 'mongoid.yml'))
2

app.rb 파일 에서 sample_restaurants 데이터베이스 의 샘플 restaurants 컬렉션 의 데이터를 나타내는 Restaurant 모델을 만듭니다.

class Restaurant
include Mongoid::Document
field :name, type: String
field :cuisine, type: String
field :borough, type: String
end
3

HTML과 Ruby 사용하여 지정된 방식으로 데이터를 표시하는 뷰를 만듭니다.

프로젝트 의 루트 수준에서 views라는 디렉토리 만듭니다. 그런 다음 list_restaurants.erb이라는 파일 만듭니다. 다음 코드를 list_restaurants.erb 파일 에 붙여넣습니다.

<!DOCTYPE html>
<html>
<head>
<title>Restaurants List</title>
</head>
<body>
<h1>Restaurants List</h1>
<table border="1">
<tr>
<th>Name</th>
<th>Cuisine</th>
<th>Borough</th>
</tr>
<% @restaurants.each do |restaurant| %>
<tr>
<td><%= restaurant.name %></td>
<td><%= restaurant.cuisine %></td>
<td><%= restaurant.borough %></td>
</tr>
<% end %>
</table>
</body>
</html>
4

app.rb 파일 에서 다음 코드와 같이 list_restaurants라는 get 경로를 추가합니다.

get '/list_restaurants' do
@restaurants = Restaurant
.where(name: /earth/i)
erb :list_restaurants
end

이 경로는 name 필드 값에 문자열 "earth"가 포함된 Restaurant 문서를 검색합니다. 이 경로는 list_restaurants 뷰를 사용하여 결과를 렌더링합니다.

5

결과를 렌더링하기 위해 뷰를 생성하는 대신 to_json 메서드를 사용하여 결과를 JSON 형식으로 표시할 수 있습니다.

결과를 JSON 문서로 반환하려면 app.rb 파일 의 list_restaurants 경로를 다음 코드로 바꿉니다.

get '/list_restaurants' do
restaurants = Restaurant
.where(name: /earth/i)
restaurants.to_json
end
6

애플리케이션 루트 디렉토리 에서 다음 명령을 실행하여 Ruby 웹 서버 시작합니다.

bundle exec ruby app.rb

서버 시작되면 애플리케이션 이 포트 4567에서 실행 을 나타내는 다음 메시지가 출력됩니다.

[2024-10-01 12:36:49] INFO WEBrick 1.8.2
[2024-10-01 12:36:49] INFO ruby 3.2.5 (2024-07-26) [arm64-darwin23]
== Sinatra (v4.0.0) has taken the stage on 4567 for development with backup from WEBrick
[2024-10-01 12:36:49] INFO WEBrick::HTTPServer#start: pid=79176 port=4567
7

웹 브라우저에서 http://localhost:4567/list_restaurants URL 엽니다. 이 페이지에는 레스토랑 목록과 각 레스토랑에 대한 세부 정보가 표시됩니다.

렌더링된 레스토랑 목록

참고

문제가 실행 하면 MongoDB Stack Overflow 태그를 지정하다 또는 MongoDB Reddit Community에서 도움을 요청하세요. 이 페이지의 오른쪽에 있는 Rate this page 탭 사용하여 피드백 제출 수도 있습니다.

돌아가기

연결 구성