title: Rails 5: collection_check_boxes from enum (hash)
body: <p>How to create collection_check_boxes from hashed <code>enum</code>:</p>
  
  <pre><code>class User &lt; ApplicationRecord
    has_many :roles, dependent: :destroy
    accepts_nested_attributes_for :roles, allow_destroy: true
  end
  
  class Role &lt; ApplicationRecord
    belongs_to :user
  
    enum permission: {
      read_contact: 0,
      write_contact: 1,
      read_message: 2,
      write_message: 3
    }
  end
  </code></pre>
  
  <p>I tried in many ways:</p>
  
  <pre><code>= form_for(@user) do |f|
    = f.collection_check_boxes :permissions, Role.permissions, :last, :first
    = f.submit class: "button"
  </code></pre>
  
  <p>I got <code>undefined method permissions for #&lt;User:0x00007...&gt;</code></p>
  
  <p>If I try with:</p>
  
  <pre><code>= form_for(@user) do |f|
    = f.collection_check_boxes :roles, Role.permissions, :last, :first
    = f.submit class: "button"
  </code></pre>
  
  <p>User controller:</p>
  
  <pre><code>def update
    @user = User.new(user_params)
    if @user.save 
       ...
  end
  
  def user_params
    params.require(:user).permit(:roles)
  end
  </code></pre>
  
  <p>I got <code>Unpermitted parameter: :roles</code></p>
  
  <p>Despite of looking at params:</p>
  
  <pre><code>Parameters: {"utf8"=&gt;"✓", "authenticity_token"=&gt;"...", "user"=&gt;{"roles"=&gt;["", "1", "2"]}, "commit"=&gt;"Update", "id"=&gt;"3"}
  </code></pre>
  
  <p>Also this is check to create, how to uncheck to delete?</p>
  
  <p><strong>Update:</strong> Try as @Steve said I should use a nested form</p>
  
  <pre><code>= form_for(@user) do |f|
    = f.fields_for :roles do |ff|
      = ff.collection_check_boxes :permission, Role.permissions, :first, :first
    = f.submit class: "button"
  </code></pre>
  
  <p>I got a correct checked permission from database! Yay!!</p>
  
  <p>However on sending form, this is params:</p>
  
  <pre><code>Parameters: {"utf8"=&gt;"✓", "authenticity_token"=&gt;"...", "user"=&gt;{"roles_attributes"=&gt;{"0"=&gt;{"permission"=&gt;["", "read_message", "write_message"], "id"=&gt;"18"}}}, "commit"=&gt;"Update", "id"=&gt;"3"}
  </code></pre>
  
  <p>I got <code>Unpermitted parameter: :permission</code> though I have permit it in controller:</p>
  
  <pre><code>def user_params
    params.require(:user).permit(roles_attributes: %i[id permission _destroy])
  end
  </code></pre>
  
  <p>I think the params should be like this:</p>
  
  <pre><code>params = { user: {
    roles_attributes: [
      { permission: 'read_message' },
      { permission: 'write_message' },
      ...
    ]
  }}
  </code></pre>
  
  <p>Instead, what I got in params now:</p>
  
  <pre><code>params = { user: {
    roles_attributes: [
      { permission: ['', 'read_message', 'write_message' }
      ...
    ]
  }}
  </code></pre>