액션 뷰(폼 도우미 메소드)

IT(Old)/RubyOnRails-Tip 2008. 1. 22. 12:19
<% form_for :person, Lurl => {:action => "create"} do |f| %>
<p>이름: <%= f.text_field("name") %> </p>
<p>그룹: <%= f.select("group",
                                 [["A", "1"], ["B", "2"], ["C", "3"]]) %> </p>
<p>노트: <br /><%= f.text_area("note") %> </p>
<p><%= submit_tag("입력") %></p>
<% end %>

f.text_field(name, options) : 텍스트 필드를 출력해줌. 한줄의 텍스트를 입력받을 때 사용
f.text_area(name, options): TextArea 필드를 출력해줌
f.password_field(name, options): 패스워드 필드를 출력해줌.
f.hidden_field(name, options): 히든 필드를 출력해줌
f.select(name, options):콤보박스 필드를 출력해줌.
<%= f.select("group_id", @groups.map{|g| [g.name, g.id]},
                   :selected => "2", :include_blank => true) %>
=>
<select name="person[group_id]">
...

f.date_select(name, options): 날짜 입력을 위한 콤보 박스 필드를 출력해줌.
<% f.date_select("birth_date", :start_year => 2000,
                                           :end_year => 2010,
                                           :use_month_numbers => true) %>

f.datetime_select(name, options): 날짜 입력을 위한 콤보 박스 필드를 출력해 줌
f.check_box(name, options): 체크박스 필드를 출력해줌
f.radio_button(name, options): 라디오 버튼 필드를 출력해줌
f.file_field(name, options): 파일 업로드 필드를 출력해줌
submit_tag(name): html 입력 필드를 출력해줌

액션뷰 (h메소드)

IT(Old)/RubyOnRails-Tip 2008. 1. 22. 10:37
<%= h("차림표") %>
부분의 코드에서 h도우미 메소드는 인자로 받는 문자열 중에
<, >, & 등의 문자가 있을 때 이를 이스케이프 시켜주는 메소드이다. 이들 문자는 html내에서 특별하게 인식되기 때문에, 이들 문자가 텍스트 중에 그대로 사용되면, 브라우저에서 html화면이 깨져 보이게 된ㄷ.ㅏ 따라서 텍스트 데이터가 html문서의 중간에 삽이되는 경우에는 항상 h메소드를 적용하는 습관을 들이는 것이 좋다.

액션 뷰(빈줄 삽입)

IT(Old)/RubyOnRails-Tip 2008. 1. 22. 10:17
HTML코드에서 <% @name = "홍길동" %> 이 입력되었던 다리에 빈줄이 삽입된 것을 알 수 있다.
이러한 빈 줄이 삽입되지 않기를 원한다면, <% @name = "홍길동" %> 대신에 <% @name = "홍길동" =%>이라고 입력하면 된다.

필터

IT(Old)/RubyOnRails-Tip 2008. 1. 22. 10:11

필터란 액션 컨트롤러의 액션 메소드가 실행되기 이전 또는 이후에 추가적인 작업을 할 수 있게 하는 기능이다.
필터가 유용한 이유는 여러 액션 또는 컨트롤러에 공통적으로 적용될 작업을 한 곳에서 관리할 수 있기 때문이다.

필터는 액션컨트롤러 클래스의 메소드로 정의된다. 보통 하나의 필터는 여러 개의 컨트롤러 클래스에서 공통적으로 사용되는 경우가 많으므로, 모든 컨트롤러의 부모 클래스에서 정의되는 것이 일반적이다.

-application.rb

class ApplicationController < ActionController::Base
  private
  def check_login_status
    unless session[:user_id]
      redirect_to :controller => "login", Laction => "login_form"
    end
  end

end

- users_controller.rb
class UsersController < ApplicationController
 
  before_filter :check_login_status, :except => [:list, :show]
 
....

:except나 :only를 사용하여 원하는것만 적용도 가능하다.

플래시 사용예제

IT(Old)/RubyOnRails-Tip 2008. 1. 22. 10:03


class UsersController < ApplicationController
  def list
    @users = User.find(:all)
    @message = flash[:message]
  end
 
  def show
    @user = User.find(params[:id])
  end
 
  def new
    @user = User.new
  end
 
  def create
    @user = User.new(params[:user])
    if @user.save
      flash[:message] = "새로운 사용자가 추가되었습니다."
      redirect_to :action => 'list'
    else
      render :action => 'new'
    end
   
  end
end

쿠키사용예제

IT(Old)/RubyOnRails-Tip 2008. 1. 22. 09:54

옵션들
:expire = 웹 브라우저가 쿠키를 얼마나 오랫동안 보관할 것인지를 지정하는 옵션이다. :expire 옵션에는 쿠키가 유효한 최종 날짜를 지정하면 된다.
(expire옵션이 생략되는 경우, 해당 쿠키는 웹브라우저가 종료되는 순간까지만 보관된다.)

:domain = 쿠키가 사용될 도메인을 지정하는 데 사용된다. 이 옵션이 생략되면 현재 사용되고 있는 웹 애플리케이션의 도메인이 사용되는데, 이런 경우 쿠키가 다른 서브 도메인과 공유되지 않는다. 예를 들어 현재의 웹 애플리케이션이 www.mysite.co.kr도메인을 사용하고 있다면, 이 서버에서 웹 브라우저에 저장한 쿠키는 help.mysite.co.kr 도메인을 사용하는 웹 애플리케이션으로는 보내지지 않는다.
(사용법 : :domain => ".mysite.co.kr")

:path = 쿠키가 사용될 URL의 디렉토리 경로를 지정하는 데 사용된다. 예를 들어 :path => "/search" 라는 옵션을 지정하면, 이 쿠키는 URL이 www.mysite.co.kr/search로 시작되는 경우에만 서버로 보내진다. 이 옵션이 생략되면, 쿠키의 :path값으로 현재 페이지의 디렉토리 경로가 사용된다.

:secure = :secure => true 옵션을 사용하면, 쿠키가 https프로토콜이 사용되는 경우에만 보내지게 된다. HTTPS는 HTTP에 보안 기능이 추가된 프로토콜로, HTTPS를 사용하여 전송되는 모든 정보는 암호화되어 안전하게 전송된다.

class LoginController < ApplicationController

  def login_form
    reset_session
    @login = cookies[:login]
  end

  def login
    @user = User.find_by_login(params[:login])
    cookies[:login] = {:value => @user.login, :expire => 30.day.from_now}
   
    if @user && (@user.password == params[:password])
      session[:user_id] = @user.id
      redirect_to :action => "index"
    else
      flash[:error] = "로그인 ID나 비밀번호가 틀렸습니다!"
      redirect_to(:action => "index")
    end
  end

  def logout
    reset_session
    redirect_to(:action => "login_form")
  end

  def index
    if session[:user_id]
      render_text "#{User.find(session[:user_id]).name}님 환영합니다.!"
    else
      redirect_to :action => "login_form"
    end
  end
end

세션과(session) 플래시(flash) 기능 팁

IT(Old)/RubyOnRails-Tip 2008. 1. 22. 09:08

1. session : session 메소드는 해시 객체를 리턴하는데, 이 해시가 바로 세션 데이터가 저장되는 장소이다.
사용자가 로그인 된 이후에는, sessoin[:user_id]이 현재 로그인된 사용자 ID를 리턴하게 된다. 만약 현재의 사용자가 로그인되어 있지 않다면, session[:user_id]는 nil을 리턴한다.

세션기능은 기본적으로 on 상태이기 때문에 이 기능을 필요치 않은 페이지에서는
각 컨트롤러 선언부 바로 밑에
session :off
을 사용하여 중지시킬수도 있다.

2. Flash : 플래시 기능이 유용한 것은 앞에서도 설명한 바와 같이 HTTP 프로토콜이 상태를 보존할 수 없는 프로토콜이기 때문이다. 플래시는 세션과는 다르게 웹 브라우저의 바로 다음 요청까지만 데이터를 보존한다. 즉 login 액션에서 플래시에 저장된 에러 메세지는 바로 다음 요청인 login_form 액션까지만 유지되고, 그 이후에는 자동으로 삭제된다. 플래시에 대한 자세한 내용은 5.5절 '플래시'에서 다루고 있다.


사용예제
class LoginController < ApplicationController

  def login_form
    reset_session
   
  end

  def login
    @user = User.find_by_login(params[:login])
   
    if @user && (@user.password == params[:password])
      session[:user_id] = @user.id
      redirect_to :action => "index"
    else
      flash[:error] = "로그인 ID나 비밀번호가 틀렸습니다!"
      redirect_to(:action => "index")
    end
  end

  def logout
    reset_session
    redirect_to(:action => "login_form")
  end

  def index
    if session[:user_id]
      render_text "#{User.find(session[:user_id]).name}님 환영합니다.!"
    else
      redirect_to :action => "login_form"
    end
  end
end

모델 데이타의 검증

IT(Old)/RubyOnRails 2008. 1. 21. 16:50
1. validates_acceptance_of(attribute, :message => "message", :accept => "1")
     => 필드가 HTML폼의 체크박스가 선택되어 있음을 검증
2. validates_associated(object)
3. validates_confirmation_of(attribute, :message => "message")
     => HTML 폼에서 사용자의 실수를 방지하기 위해서 필드값을 중복하여 입력받을 때,
         두 필드의 값이 일치함을 검증
4. validates_each attribute do |record, attr|
      record.errors.add attr, "error_message" if condition
   end
5. validates_exclusion_of(attribute, :in => enumerable_object, :message => "message")
     => 필드값이 지정된 배열 또는 구간의 원소중 하나가 아닐 것을 검증
6. validates_format_of(attribute, :with => /regular_expression/, :message => "message")
     => 필드값의 문자열이 지정된 정규식 패턴과 일치하는지를 검증
7. validates_inclusion_of(attribute, :in => enumerable_object, :message => "message")
     => 필드값이 지정된 배열 또는 구간의 원소중 하나임을 검증
8. validates_length_of(attribute, :maximum => max, :message => "message")
     => 필드값의 문자열 길이가 지정된 범위 내에 있음을 검증
9. validates_numericality_of(value, :message => "message")
     => 필드값이 숫자임을 검증
10. validates_presence_of(attributes, :message => "message")
     => 필드에 값이 지정되지 않았거나, 필드값이 빈 문자열인 경우 에러
11. validates_size_of(attribute, :maximum => max, :message => "message")
12. validates_uniqueness_of(attributes, :message => "message")
     => 필드값이 테이블의 다른 레코드와 중복되지 않음을 검증

 

rails console사용하기 2 (activeRecord의 수정,삭제사용법)

IT(Old)/RubyOnRails 2008. 1. 21. 16:22
1. 수정

간단하다

@user = User.find(1)
@user.password = "aaa"
@user.save

2. 삭제
한개삭제
@user = User.find(3)
@user.destroy

여러개 삭제
@user = User.find(:all, conditions > ["id" >1])
@user.destroy_all

아이디로 삭제
User.delete(3)
User.delete([1, 2, 5])

조건별로 여러개 삭제
User.delete_all(["registered_on = ?", Date.today])

Model 명명규칙 관례를 따르지 않을 경우

IT(Old)/RubyOnRails-Tip 2008. 1. 21. 15:32

User < ActiveREcord:Base
  set_table_name "user_tbl"
end

와 같이 강제로 table을 지정해 주어야 된다.


TIP : User  모델 클래스는 레일스 애플리케이션이 처음 구동될 때, 데이터베이스에 연결하여 users테이블의
필드 목록을 읽어들이게 된다. users 테이블의 필드 목록을 확인한 User 모델 클래스는 각 필드에 해당하는 접근자 메소드를 동적으로 정의하여 추가한다. 데이터 베이스 테이블의 필드를 확인하고 이에 해당하는 접근자
메소드를 동적으로 추가하는 User 모델 클래스의 기능으 ActiveRecord::Base클래스로 부터 상속되고 있다.