웹어플리케이션을 제작할 때 퍼블리셔는 프론트엔드를 제일선에서 담당하는 매우 중요한 역할을 수행한다. 레일스를 이용해서 웹개발할 때도 예외는 아니다. 그러나 레일스는 MVC 디자인 패턴이 완벽하게 통합되어 있어서 뷰(view)단에서 퍼블리셔의 능력을 한껏 발휘할 수 있다. 또한 bootstrap-sass 젬 덕분에 레일스에서 Twitter Bootstrap을 매우 쉽게 사용할 수 있고 simple_form 젬과 함께 사용하면 뷰단의 디자인을 비전문가의 입장에서도 비교적 간단하게 해결할 수 있어 매우 편리하다.
그러나 simple_form 젬을 처음 사용할 때는 wrapper
클래스에 대한 이해 부족으로 라디오버튼과 체크박스 표시를 자유자재로 사용하기 힘들다.
이 글에서는 예제 코드를 통해서 하나씩 해결해 보도록 하겠다.
Twitter Bootstrap 3를 레일스의 asset pipeline으로 쉽게 사용할 수 있도록 해 주는 젬인 bootstrap-sass 젬과 html 폼을 간단하게 작성할 수 있도록 해주는 simple_form 젬을 프로젝트 루트 디렉토리에 있는 Gemfile
파일에 추가하고 터미널의 커맨드라인에서 bundle install
명령을 실행한다. Gemfile
은 프로젝트 루트 디렉토리에 있다.
...
gem 'bootstrap-sass'
gem 'simple_form'
...
이 두 젬을 사용하기 위해서 몇가지 셋업 과정이 필요한데, 이것은 각 젬의 github 저장소를 참고하면 힘들지 않게 할 수 있다.
- bootstrap-sass : https://github.com/twbs/bootstrap-sass
- simple_form : https://github.com/plataformatec/simple_form
위의 화면과 같은 폼을 만들어 보는 것으로 시작해 보자.
위에서 사용한 Post
모델은 title
, content
, published
라는 세개의 속성을 가지고 있으며 published
속성은 boolean
형의 데이터를 가지는 것으로 한다.
레일스의 scaffold
제너레이터를 이용하여 Post
리소스를 아래와 같이 커맨드라인에서 생성한다.
$ rails g scaffold Post title content:text published:boolean
그러면 아래와 같은 마이그레이션 클래스(201xxxxxxx0205_create_posts.rb)
가 db/migrate
디렉토리에 생성된다. 여기서 파일명 앞에 붙은 숫자는 타임스탬프이며 파일이 생성될 때 자동으로 붙게 된다. 따라서 파일 생성시점에 따라 이 숫자값은 다르게 표시될 수 있다.
class CreatePosts < ActiveRecord::Migration
def change
create_table :posts do |t|
t.string :title
t.text :content
t.boolean :published, default: false
t.timestamps null: false
end
end
end
위 소스코드의 6번 라인에서 같이 default: false
옵션을 추가해서 새 레코드가 생성될 때 published
의 값이 기본값(디폴트)으로 지정한 false
값을 같도록 한다.
마이그레이션 작업(커맨드라인 라인에서 rake db:migrate
명령을 실행함)을 하여 실제로 데이터베이스 테이블을 생성해야 한다.
로컬 웹서버를 시작한 후 브라우저에서 http://localhost:3000
으로 연결해 보자. smoke 페이지가 보이면 제대로 레일스 프로젝트가 생성된 것이다.
이제 http://localhost:3000/posts
로 이동한 후 하단에 있는 New Post
링크를 클릭하면 데이터 입력 폼이 보이게 된다. 글의 시작부분에서 보여준 페이지 폼 내용을 보면 각 속성의 이름이 한글로 표시된 것을 알 수 있다. 이것은 레일스에서 기본으로 지원하는 로케일(locale)을 사용한 것이다.
이와 같이 표시하기 위해서는 두가지 작업을 추가로 해 주어야 한다.
첫째로, config/application.rb
파일을 열어 21번째 줄에 코멘트처리되어 있는 부분에서 # 표시를 제거하고 :de
대신에 :ko
라는 심볼값으로 지정한다.
둘째로, config/locales
디렉토리에 activerecord.ko.yml
파일을 생성하고 아래와 같이 작성한다.
ko:
activerecord:
models:
post: 포스트
attributes:
post:
title: 제목
content: 내용
published: 공개여부
로컬 웹서버를 다시 시작한 후 브라우저에서 http://localhost:3000/posts/new
로 다시 연결하면 속성명이 한글로 표시되는 것을 확인할 수 있을 것이다.
다음으로, 이 글의 주제인 라디오버튼과 체크박스 표시 부분에 주목하도록 하자.
이미 Gemfile로 등록한 후 셋업해 놓은 bootstrap-sass 와 simple_form 젬 덕분에 아래와 같은 간단한 소스로 위의 폼을 표시할 수 있게 된다.
app/views/posts/new.html.erb :
<h1>New Post</h1>
<%= render 'form' %>
<%= link_to 'Back', posts_path %>
app/views/posts/_form.html.erb :
<%= simple_form_for(@post) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :title %>
<%= f.input :content, input_html: { rows: 10 } %>
<%= f.input :published %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
위와 같은 간단한 코드를 작성하므로써 폼을 멋지게 표시할 수 있게 된다. 위의 소스코드 7번 라인을 보자. 폼 객체의 input
메소드에 :published
라는 속성명을 심볼로 지정해 주면 체크박스 엘리먼트와 공개여부
라는 라벨이 표시된다. 와우~ 놀랍지 않은가…
또한, 몇가지 조작을 하면 boolean
형의 published
속성값을 폼에서 입력 받기 위해서 아래와 같이 표시할 수 있다.
아래의 소스코드 7번 라인의 f.input :published
부분의 추가 옵션 부분을 주목하기 바란다.
<%= simple_form_for(@post) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :title %>
<%= f.input :content, input_html: { rows: 10 } %>
<%= f.input :published, as: :radio_buttons, item_wrapper_class: :with_label, collection_wrapper_tag: :div, collection_wrapper_class: 'radio-group' %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
위의 추가 옵션을 제대로 표시하기 위해서 with_label
, radio-group
이라는 두개의 클래스 정의를 추가해 주어야 한다.
.form-actions {
background-color: #eaeaea;
border-top: 1px solid #ccc;
padding: 1em 1em 1.5em;
margin:1.5em 0 1.5em;
border-radius: 0 0 5px 5px;
}
.with_label {
display:inline;
margin-right: 1.5em;
}
.radio-group {
border:1px solid #ccc;
border-radius:4px;
padding:.5em 1em .5em;
box-shadow:inset 0 1px 1px rgba(0, 0, 0, 0.075);
.radio {
display: inline;
&:first-child {
margin-right:1.5em;
}
}
}
h1,h2,h3,h4 {
font-weight: bolder;
}
요약하면, f
라는 폼 객체의 input
메소드에 세가지 옵션을 추가해 주었다.
as: :radio_buttons
(simple_form 에서 미리 정의해 놓은 표시 형태)item_wrapper_class: :with_label
(라벨 사이의 간격을 동일하게 유지함)collection_wrapper_tag: :div
collection_wrapper_class: :radio_group
결과로 만들어지는 HTML 태그는 아래와 같다.
<div class="form-group radio_buttons optional post_category">
<label class="radio_buttons optional control-label">Category</label>
<div class="radio-group">
<span class="radio with_label">
<label for="post_category_life">
<input id="post_category_life" class="radio_buttons optional" name="post[category]" type="radio" value="life" />life
</label>
</span>
<span class="radio with_label">
<label for="post_category_computer">
<input id="post_category_computer" class="radio_buttons optional" name="post[category]" type="radio" value="computer" />
computer
</label>
</span>
<span class="radio with_label">
<label for="post_category_study">
<input id="post_category_study" class="radio_buttons optional" name="post[category]" type="radio" value="study" />
study
</label>
</span>
</div>
</div>
오늘은 여기까지 소개한다.
다음은 복수개의 boolean
형 속성을 그룹으로 묶어서 위와 같은 포맷으로 표시하는 방법에 대해서 설명하도록 하겠다.
소스코드 :