Rails 간단 한 연습

레일 스에 대한 간단 한 연습
학생 과 교사 의 CRUD, 그리고 간단 한 ajax 응용학생 과 교 사 는 일대일 관 계 를 가진다.
model 은:
class Student < ActiveRecord::Base
  belongs_to :teacher
end
class Teacher < ActiveRecord::Base
  has_many :students,:dependent=>:delete_all
end

 
migrate 는:
class CreateTeachers < ActiveRecord::Migration
  def self.up
    create_table :teachers,:force=>true do |t|
      t.column :name,:string
    end
  end

  def self.down
    drop_table :teachers
  end
end

class CreateStudents < ActiveRecord::Migration
  def self.up
    create_table :students,:force=>true do |t|
      t.column :name,:string
      t.column :teacher_id,:integer
      add_index :students,:teacher_id
    end
  end

  def self.down
    drop_table :students
  end
end

 
 
rake db: migrate 를 실행 하면 데이터베이스 에 외부 키 를 사용 하지 않 고 teacher 만 사용 하 는 것 을 볼 수 있 습 니 다.id 위 에 색인 추가
 
컨트롤 러 코드: 모든 학생 과 교 사 를 표시 하고 학생 과 교 사 를 추가 하고 삭제 하 는 기능
#coding:utf-8
class HomeController < ApplicationController
  #    
  def index
    list
    render :action => "index"
  end

  #           ,     ,     index
  def new
    #               
    if check_n
      entity = Student.new
      unless params[:teacher_id].nil?
        unless params[:teacher_id]=="0"
          entity.teacher = Teacher.find params[:teacher_id]
        end
      end
      if check_type == "teacher"
        entity = Teacher.new
      end
      entity.name = @name
      entity.save
      flash[:error] = "OK"
    end
    redirect_to :action => "index"
  end

  #     /  
  def delete
    begin
      #         ,      
      logger.debug "debug================================="
      logger.debug "the type and id is type:#{params[:type]},id:#{params[:id]}"
      if params[:type] and params[:type]=="student"
        Student.destroy(params[:id])
      else
        t = Teacher.find params[:id]
        #           id
        id_array = t.student_ids.to_s
        t.destroy
        logger.debug "debug================================="
        logger.debug "the array is #{id_array.to_s}"
      end
    rescue =>e
      logger.debug(e)
      #              
      # render :text => e.to_s
      return
    end
    #                       id      
    if id_array.nil?
      render :text => "OK"
    else
      render :text => id_array
    end
  end
  private
  #           
  def list
    @students = Student.find :all
    @teachers = Teacher.find :all
    @teacher_name = []
    for st in @students
      th = st.teacher
      unless th.nil?
        @teacher_name << st.teacher.name
      else
        @teacher_name << "none"
      end
      #        logger.debug "debug================================="
      #        logger.debug "the student's teacher is #{st.teacher}"
    end
  end
  #            
  def check_n
    @name = params[:name]
    logger.debug "debug================================="
    logger.debug "this name is #{@name}"
    if @name.nil? or @name.strip.empty?
      flash[:error] = "name should not be empty."
      return false
    else
      return true
    end
  end
  #            
  def check_type
    type = params[:type]
    logger.debug "debug================================="
    logger.debug "the type is #{type}"
    if type.nil?
      raise "     。"
    elsif type == "student"
      return type
    elsif type == "teacher"
      return type
    else
      raise "     "
    end
  end
end

  
 index. rhtml 은 다음 과 같 습 니 다.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <base href="/"/> 
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
    <title>test</title>
    <script type="text/javascript" src="javascripts/prototype.js"></script>
    <script type="text/javascript">
      function addEvent(){
        //   a        
        $$("a").each(function(a){
          a.observe("click",deleteEntity)
        })
      }
      //          
      function teacherList(){
        select = document.getElementById("type")
        value = select.options[select.selectedIndex].text
        if (value=="  ")
          $('teacher_id').show()
        else{
          $("teacher_id").hide()
        }
      }
      //      id       Ajax  
      function deleteEntity(e){
        a = Event.element(e)
        //  a   id  ,                id
        id = a.identify()
        type = "student"
        if(a.hasClassName("teacher")){
          type="teacher"
        }
        //          
        ajax(a,id,type)
      }
      function ajax(a,id,type){
        //  alert(id)
        new Ajax.Request("home/delete",{parameters:{id:id,type:type},onSuccess:callback})
        function callback(data){
          //            
          var result = data.responseText
          removeLi(a)
          //       OK,        
          if (result!="OK")
            refreshList(result)
        }
      }
      function refreshList(array){
        ids = eval(array)
        if(ids.length==0) return
        $$("ul")[0].childElements().each(function(li){
          li.childElements().each(function(a){
            id = a.identify()
            for(i=0;i<ids.length;i++){
              if (id == ids[i])
                removeLi(a)
            }
          })
        })
      }
      function removeLi(a){
        a.ancestors()[0].remove()
      }
      //     
      Event.observe(window,"load",addEvent)
    </script>
  </head>
  <body>
    <p>    :</p>
    <ul>
      <% @students.each_index do |index| %>
        <li>
              :<%=@students[index].name%>
               :<%=@teacher_name[index]%>
          <a  href="javascript:void(0);" class="student" id="<%=@students[index].id%>">  </a>
        </li>
      <%end%>
    </ul>
    <p>    :</p>
    <ul>
      <% @teachers.each do |teacher| %>
        <li>
              :<%=teacher.name%>
          <a href="javascript:void(0);" class="teacher" id="<%=teacher.id%>">  </a>
        </li>
      <%end%>
    </ul>
    <p />
    <hr />
    <p>    /  <br /></p>
    <% form_tag("home/new") do-%>
        :<input name="name"/>
      <p />
        :
      <select onchange="teacherList()" name="type" id="type">
        <option value="student">  </option>
        <option value="teacher">  </option>
      </select>
      <div id="teacher_id">
             :
        <select name="teacher_id">
          <option value="0">  </option>
          <% @teachers.each do |teacher| %>
            <option value="<%=teacher.id%>"><%=teacher.name%></option>
          <%end%>
        </select>
      </div>
      <p />
      <input type="submit" value="  "/>
    <%end-%>
    <p>    :<span style="color: red"><%=flash[:error]%></span></p>
  </body>
</html>

 
위의
/ / 교사 리스트 등록 시간 멀미
/ / 배경 으로 삭제 요청 기절 보 내기
마지막 '헐' 을 추가 하지 않 으 면 이 오류 가 발생 합 니 다. invalid byte sequence in GBK.이상 하 네요. bug 일 수도 있어 요.ruby API 문 서 를 보 니 Encoding. default 가 추가 되 었 습 니 다.internal = "UTF - 8" 과 Encoding. defaultexternal = "UTF - 8" 부터 applicationcontroller. rb 에서 이 기괴 한 문 제 를 해결 할 수 있 습 니 다.
또 하나의 문제: 폼 이 중국 어 를 입력 하면 데이터베이스 에 중국 어 를 저장 할 때 도 incompatible character encodings: GBK and ASCII - 8BIT 의 오 류 를 보고 합 니 다.
 
ruby 는 ruby 1.9.1 버 전 입 니 다.
rails 는 rails 2.3.8 버 전 입 니 다.

좋은 웹페이지 즐겨찾기