Rails Form Helper: collection_check_boxes

Nathan Lee
Change or Die!
Published in
3 min readMay 15, 2018

在實作ALPHAcamp大航道計畫期末考題目「Dojo Forum」時,其中有一個user story 「使用者張貼文章(post)時,可以選擇 Category (多選),例如 [ ] 商業類 [ ] 技術類 [ ] 心理類」。需要提供check_box方塊讓使用者可以勾選文章(post)所屬的分類(category)。

所以透過 collection_check_boxes 這個rails form helper來完成這個user story的功能。

其中相關的table跟欄位如下:

首先在post 和 category model設定關聯:

class Post < ApplicationRecord  has_and_belongs_to_many :categoriesendclass Category < ApplicationRecord  has_and_belongs_to_many :postsend

然後在create categories_posts 這個 join table,透過以下指令建立migration檔案~

$ rails g migration create_categories_posts category_id:integer post_id:integer

開啟migration檔案會看到以下內容:

class CreateAtegoriesPostsTable < ActiveRecord::Migration[5.1]
def change
create_table :categories_posts do |t|
t.integer :category_id
t.integer :post_id
end
end
end

然後執行以下指令建立table跟欄位:

$ rails db:migrate

接著在對應的rails form內加入collection_check_boxes這個helper,

<%= f.collection_check_boxes :category_ids, Category.all, :id, :name do |i| %>

<%= i.check_box %>
<%= i.label %>

<% end %>

依據我的category內的data最後會以類似下圖的方式呈現出來,

提供check_box方塊讓使用者可以勾選文章(post)所屬的分類(category)

更多的collection_check_boxes介紹可以參照以下資訊:

  1. collection_check_boxes
  2. Using Collection_Check_Boxes to Simplify User Interactions
  3. Has Many Through Checkboxes in Rails 3.x, 4.x and 5
  4. Ruby on Rails 實戰聖經: RESTful 應用實作 多對多 Resources

--

--