Ruby on Rails MVC

Toggle Space Navigation Tree
Space Map

Ruby on Rails의 기본 디렉토리 구조

화면 캡쳐 필요함.

Ruby on Rails의 MVC 기본 아키텍처

Agile Web Development 12 페이지 그림 2.1

각 Layer별 pseudo 코드

Model

contact.rb
class Contact < ActiveRecord::Base
end
  • 위 코드는 contacts라는 테이블과의 매핑을 담당하고 있는 ActiveRecord 클래스이다. 위 코드 두 줄이면 기본적인 CRUD에 대한 처리는 완료된 것이다.
  • Model 클래스는 기본적으로 "app/models" 디렉토리에 위치한다.

Controller

mytest_controller.rb
class MyTestController < ApplicationController
    def index 
        render_text "Hello World!"
    end
end
  • 위 코드를 통하여 하나의 Controller 클래스가 완성된 것이다. http://localhost:3000/MyTest를 통하여 접근하면 "Hello World!"가 출력될 것이다.
  • > ruby script\generate controller Mytest Command를 이용하여 기본 템플릿 파일을 생성하는 것이 가능하다.
  • Controller 클래스는 기본적으로 "app/controllers" 디렉토리에 위치한다.

View

  • Controller와 Model을 완성하게 되면 기본적인 CRUD를 위한 디폴트 화면이 나타나는 것을 확인할 수 있다. 만약 이 View 화면을 변경하고자 한다면 다음과 같이 개발하는 것이 가능하다.
app/views/modulename/methodName.rhtml
<html>
<head>
<title>All Recipes</title>
</head>
<body>

<h1>Online Cookbook - All Recipes</h1>
<table border="1">
 <tr>
  <td width="80%"><p align="center"><i><b>Recipe</b></i></td>
  <td width="20%"><p align="center"><i><b>Date</b></i></td>
 </tr>

 <% @recipes.each do |recipe| %>
  <tr>
   <td><%= link_to recipe.title, :action => "show", :id => recipe.id %></td>
   <td><%= recipe.date %></td>
  </tr>
 <% end %>
</table>
<p><%= link_to "Create new recipe", :action => "new" %></p>

</body>
</html>
  • View 화면에서도 Ruby 언어의 사용이 가능하다는 것을 알 수 있다.
  • View 파일은 app/views 디렉토리 아래에 modulename 아래에 위치하게 된다.

참고문서

Enter labels to add to this page:
Please wait 
Looking for a label? Just start typing.