블로그 이미지
언제나 늘 푸른 소나무처럼. 자신의 의지로 오롯이 서기
예섬수진

공지사항

최근에 올라온 글

최근에 달린 댓글

최근에 받은 트랙백

글 보관함

calendar

1 2 3 4 5 6
7 8 9 10 11 12 13
14 15 16 17 18 19 20
21 22 23 24 25 26 27
28 29 30

Rails]Rails를 이용한 DB Table 생성(sqlite3)

2009. 12. 14. 23:25 | Posted by 예섬수진
rails web으로 기본 골격 생성

cd web
rake db:create로 DB 생성

ruby script/generate model build_info build_type:string model_name:string build_time:string rom_file:string 로 model 생성
  ※ model을 이용하면 DB의 CRUD를 할 수 있음
  ※ 나는 model 이름을 build_info라고 하였으나, 실제 모델 이름은 BuildInfo 임
       - web\app\models\build_info.rb
class BuildInfo < ActiveRecord::Base
            end

rake db:migrate DB에서 적용안된 내용을 적용하기 위함

생성된 table 이름 확인
  - web\db\schema.db에 가면, build_infos로 테이블이 생성된 것을 확인할 수 있음
       create_table "build_infos", :force => true do |t|
         t.string   "build_type"
         t.string   "model_name"
         t.string   "build_time"
         t.string   "rom_file"
         t.datetime "created_at"
         t.datetime "updated_at"
       end

Mapping
   - web\config\routes.rb에서 다음 라인을 2째 줄에 추가함
       map.resources :build_infos

ruby script/generate controller build_info add get를 이용하여 Controller 생성
   1. web\app\controllers\build_info_controller.rb 수정
       class BuildInfoController < ApplicationController
          def add
             @build_type = params['build_type']
             @model_name = params['name']
             @build_time = params['started_at']
             @rom_file = params['rom_file']
             BuildInfo.create(:build_type => @build_type, :model_name => @model_name, :build_time => @build_time, :rom_file => @rom_file)
 
             @build_infos = BuildInfo.all
             respond_to do |format|
                 format.html # add.html.erb
                 format.xml  { render :xml => @build_infos }
             end
          end

          def get
              @build_infos = BuildInfo.all
              respond_to do |format|
                   format.html # get.html.erb
                   format.xml  { render :xml => @build_infos }
              end
           end
        end

    2. web\app\views\build_info의 add.html.erb/get.html.erb를 아래와 같이 수정함
        <h1>Listing build_info</h1>
        <table>
              <% @build_infos.each do |build_info| %>
                <tr>
                     <td><%=h build_info.build_type %></td>
                     <td><%=h build_info.model_name %></td>
                     <td><%=h build_info.build_time %></td>
                     <td><%=h build_info.rom_file %></td>
                </tr>
              <% end %>
         </table>

웹서버 실행을 ruby script/server를 실행함

DB Table에 해당 Record가 삽입되었는지 확인하려면, 주소창에 다음을 입력함
http://localhost:3000/build_info/add?build_type=target&name=BlueMT&started_at=091214_12000&rom_file=kernrom