Ruby on Rails:将表单复选框保存到 Postgres 中的布尔值


Rails

菜鸟在这里,我如何获得一个 Rails 表单来保存布尔复选框到postgres?我尝试了几十种在网上找到的东西,但没有一个有效。无论我做什么,Postgres 数据库中的条目都是"空"。这是我的模型(模式(:

ActiveRecord::Schema.define(version: 20171227200151) do
  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"
  create_table "notes", force: :cascade do |t|
    t.string "note_title"
    t.string "note_text"
    t.boolean "note_scratch", default: false, null: false
    t.boolean "note_info"
    t.boolean "note_reminder"
    t.boolean "note_task"
    t.string "note_tags"
    t.date "note_remind_date"
    t.time "note_remind_time"
    t.integer "note_archived"
    t.date "note_archived_date"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
  end
end

视图:

<%= form_with scope: :note, url: notes_path, local: true do |f| %>
  <p>
    <%= f.label :note_title %><br>
    <%= f.text_field :note_title %>
  </p>
  <p>
    <%= f.label :note_text %><br>
    <%= f.text_area :note_text %>
  </p>
  <p>
    <%= f.label :notes_scratch, "Scratch" %>
    <%= f.check_box :notes_scratch %>
    <%= f.label :notes_info, "Info" %>
    <%= f.check_box :notes_info %>
    <%= f.label :notes_reminder, "Reminder" %>
    <%= f.check_box :notes_reminder %>
    <%= f.label :notes_task, "Task" %>
    <%= f.check_box :notes_task %>
  </p>
  <p>
    <%= f.label :note_tags %><br>
    <%= f.text_field :note_tags %>
  </p>
  <p>
    <%= f.label :note_remind_date %><br>
    <%= f.date_field :note_remind_date %>
  </p>
  <p>
    <%= f.label :note_remind_time %><br>
    <%= f.time_field :note_remind_time %>
  </p>
  <%= f.submit %>
<% end %>

控制器:

class NotesController < ApplicationController
  def new
  end
  def create
# for testing
  # render plain: params[:note].inspect
    @note = Note.new(note_params)
    @note.save
    redirect_to @note
  end
  private
    def note_params
      params.require(:note).permit(:note_title, :note_text, :note_scratch, :note_info, :note_reminder, :note_task, :note_tags, :note_remind_date, :note_remind_time, :note_archived, :note_archived_date)
  end
end

如果我只是呈现表单结果,它将复选框显示为 1,但它在数据库中总是显示为 Null,即使我将数据类型设置为 Integer(希望它会存储 1(。所有其他字段都记录得很好。只有复选框不起作用。

感谢您提供的任何帮助!

-砖

查看您的note_params(和schema.rb(:

def note_params
  params.require(:note).permit(:note_title, :note_text, :note_scratch, :note_info, :note_reminder, :note_task, :note_tags, :note_remind_date, :note_remind_time, :note_archived, :note_archived_date)
end

在您看来:notes_*必须是单数的,因为您的架构note_*

最新更新