ruby-on-railsrubyenumsnested-attributesnested-form-for

How to use enum with checkbox rails


I want to create a question list, to decide that question has multiple correct answer or not, I use a checkbox field:

<div>
  <%= ff.label :multi_correct, t(".multi"), class: "field-label" %>
  <%= ff.check_box :multi_correct %>
</div>

Here's my question model

class Question < ApplicationRecord
...
  enum multi_correct: {no: 0, yes: 1}
end

When I submit the form, it returns an error said '0' is not a valid multi_correct

My schema.rb:

  create_table "questions", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
    t.string "content"
    t.integer "multi_correct"

How can I make this checkbox work? When it is unchecked it should send 0 to database and vice versa.


Solution

  • Oh nvm, Here's the solution

    <%= ff.check_box :multi_correct, {}, "yes", "no" %>
    

    The first one is checked value, the second one is unchecked