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

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 입력 필드를 출력해줌

액션뷰 (기본도우미 메소드)

IT(Old)/RubyOnRails 2008. 1. 22. 11:43
숫자 및 텍스트를 포맷하는 도우미 메소드

- number_with_delimiter(num(숫자에서 세자리마다 쉼표를 찍어줌)
  <%= number_woth_Delimiter(1562000) %>
  => 1,562,000

- number_with_precision(num, digits): 소수를 표시할 때, 소수점 이하 자리수를 제한하여 표시해줌, 두 번째 인자는 소수점 이하 자리수를 지정함. 두 번째 인자는 선택사항으로 지정하지 않으면 소수점이 세 자리까지 표시됨
  <% number_with_precision(200.0, 1 %>
  => 66.7
  <% number_With_precision(200.0/3) %>
  => 66.667

- number_to_human_size(num) : 숫자를 바이트로 계산하여, 사람이 읽기 편한 단위(Byte, KB, MB등)로 변환해줌
  <%= number_to_human_size(31270) %>
  => 30.5KB

- truncate(str,length) : 전체 문자열의 길이가 length를 넘지 않도록 str의 끝을 잘라줌
  <%= truncate("무궁화 꽃이 피었습니다", 10) %>
  => 무궁화 꽃이 ...

- highlight(str, word): str안의 텍스트에서 word로 넘겨받은 문자열이 나타날 때마다 <strong> 태그를 사용하여 강조해줌
  <%= highlight("무궁화 꽃이 피었습니다.", "꽃") %>
  => 무궁화 <strong class=highlight">꽃</strong>이 피었습니다.

- simple_format(str) : 텍스트를 HTML로 변환

이미지 태그 도우미 메소드
- image_tag(source, html_options): <img> 태그를 출력해줌, html_options 부분은 해시로 데이터를 전달받으며, :size, :class, :alt 옵션 등을 사용할 수 있다.

<%= image_tag("company_logo.gif", :size => "80x30",
                                                   :class => "logo",
                                                   :alt => "회사 로고") %>
<img src="/images/company_logo.gif" class="logo" width="80" height="30" alt="회사 로고" />

링크 도우미 메소드
- link_to(name, options, html_options) :<a>태그를 출력해줌. options 부분은 해시로 데이터를 전달받으며, :controller, :action, :id등 해당 라우팅의 URL패턴에 사용되는 모든 요소를 옵션으로 사용할 수 있다. html_options부분은 <a>태그에서 사용되는 html옵션을 해시로 전달받으며, :class, :popup, :confirm, :method등을 사용할 수 있다.

<%= link_to("프로필 보기",
                 {:controller => "users", :action => "show", :id => @user},
                 {:popup => ['Help', 'width=320, height=400'], :class => "info"}) %>

=>
<a href="/users/show/41" class="info" onclick="window.open(this.href, '프로필','width=320, height=400');
return false;">프로필 보기 </a>

액션뷰 (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

모델 데이타의 검증

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])

rails console사용하기 1 (activeRecord의 find 사용법)

IT(Old)/RubyOnRails 2008. 1. 21. 16:07
1.시작
ruby script/console
Loading development environment (Rails 2.0.2)
>>

위에서 >> 프롬프트는 루비의 irb프롬프트이다. 여기에서는 단순히 irb유틸리티를 실행한 것이 아니라
레일스 애플리케이션의 콘솔을 시작한 것이기 때문에, 앞에서 정의했던 User모델 클래스를 사용하는 것이
가능하다.

2. Data 입력
>> @user = User.new
=> #<User id: nil, name: nil, login: nil, password: nil, registered_on: nil>
>> @user.name = "jolaking"
=> "jolaking"
>> @user.login = "jola"
=> "jola"
>> @user.password = "jola"
=> "jola"
>> @user.registered_on = Date.today
=> Mon, 21 Jan 2008
>> @user.save
=> true     ==> 저장이 성공되었음을 표시한다.
사용자 삽입 이미지

Data 확인



다른방법
>>  @user = User.new(:name => "jolaking2",
?>  :login => "jola2",
?>  :password => "jola2",
?>  :registered_on => Date.today)
=> #<User id: nil, name: "jolaking2", login: "jola2", password: "jola2", registe
red_on: "2008-01-21">
>> @user.save
=> true
>>

사용자 삽입 이미지

3. Data Retrieve

?> @user = User.find(1)
=> #<User id: 1, name: "jolaking", login: "jola", password: "jola", registered_o
n: "2008-01-21">
>> @user = User.find(2)
=> #<User id: 2, name: "jolaking2", login: "jola2", password: "jola2", registere
d_on: "2008-01-21">
>> @user = User.find(3)
ActiveRecord::RecordNotFound: Couldn't find User with ID=3
        from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record
/base.rb:1267:in `find_one'
        from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record
/base.rb:1250:in `find_from_ids'
        from c:/ruby/lib/ruby/gems/1.8/gems/activerecord-2.0.2/lib/active_record
/base.rb:504:in `find'
        from (irb):27
>>

주의할점 registered_on 메소드는 Date객체를 리턴하기 때문에 여기에서는 리턴된 Date 객체의
to_s 메소드를 호출하여 이를 문자열로 반환해야 된다.
find_by_xxxx 사용하기

?> @user = User.find_by_login("jola")
=> #<User id: 1, name: "jolaking", login: "jola", password: "jola", registered_o
n: "2008-01-21">
>> @user = User.find_by_login("jola2")
=> #<User id: 2, name: "jolaking2", login: "jola2", password: "jola2", registere
d_on: "2008-01-21">
>> @user = User.find_by_login("jola3")
=> nil >> 값이 없으면 nil

보다 복잡한 검색조건으로 찾기

?> str = "jola2"
=> "jola2"
>> @user = User.find(:first, :conditions => ["login=?", str])
=> #<User id: 2, name: "jolaking2", login: "jola2", password: "jola2", registere
d_on: "2008-01-21">
>>

여기서 :first는 첫번째 record의 return을 의미하고,
:all로 사용하면 배열로 여러 record를 받는다.

2가지 조건 이상 사용하면 다음과 같이 사용한다.
?> @user = User.find(:first, :conditions => ["login=? AND password=?" , "jola","jola"])
=> #<User id: 1, name: "jolaking", login: "jola", password: "jola", registered_on: "2008-01-21">


이쯤에서 사용되는 옵션을 정리하면
:first or :all = 첫번째 또는 전체
:conditions = Where 조건절 기술
:order        = 정렬방식
:limit          = 불러올 Record갯수
:offset        = 지정된 숫자만큼 레코드를 건너뛰고, 그다음부터 리턴
:readonly    = 리턴되는 레코드를 읽기 전용으로 만듦

conditions에 like 문을 사용하고자 한다면
:conditions = > ["login like ?", query + "%"]

직접 SQL문 입력가능

@group = Group.find_by_sql("SELECT ..... FROM aaa WHERE....");

다음에서 group값을 사용하고자 하면
@group[0].name 이런식으로
사용해야 된다.