오늘은 지난 글에 이어서 문자열 속성을 가지는 필드에 대해서 라디오버튼 그룹 또는 SELECT
태그를 적용하는 방법을 알아보자.
위의 동영상에서 보는 바와 같이 Post
모델에 category
라는 문자열 필드를 추가하여 하나는 라디오버튼 그룹으로 표시하고 다른 하는 SELECT
태그문을 사용하여 표시하였다. 기존의 posts
테이블에 category
라는 문자열 속성을 추가해 보자.
$ rails g migration add_category_to_posts category:string
위의 명령으로 생성된 마이그레이션 파일을 열고 디폴트 값(“”)을 지정한다.
class AddCategoryToPosts < ActiveRecord::Migration
def change
add_column :posts, :category, :string, default: ""
end
end
그리고 app/views/posts/_form.html.erb 파일을 열고 아래와 같이 수정한다.
<%= simple\_form_for(@post) do |f| %>
<%= f.error_notification %>
<div class="form-inputs">
<%= f.input :category, as: :radio_buttons, item_wrapper_class: :with_label, collection: [['없음',''],['life','0'],['study','1'],['computer','2']], collection_wrapper_tag: :div, collection_wrapper_class: 'radio-group' %>
<%= f.input :category, collection: [['life','0'],['study','1'],['computer','2']], prompt: '없음' %>
<%= f.input :title %>
<%= f.input :content, input_html: { rows: 10 } %>
<%= f.input :published, as: :radio_buttons, collection_wrapper_tag: :div, collection_wrapper_class: 'radio-group' %>
</div>
<div class="form-actions">
<%= f.button :submit %>
</div>
<% end %>
rake
의 db:migrate
태스크를 실행하여 테이블에 반영한 후 브라우저에서 http://localhost:3000/posts/new
로 연결해 보자.
아마도 위의 동영상 같이 보이게 될 것이다.
오늘을 여기까지 설명한다. 다음은 여러 개의 boolean
형 속성을 하나의 라디오버튼 그룹처럼 보이도록 하는 것을 구현해 보기로 할 것이다.
소스코드 :