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

时间:2018-01-03 22:02:03

标签: ruby-on-rails ruby postgresql

这里有Rails noob,如何获取Rails表单来保存postgres的布尔复选框?我已经尝试了几十种我在网上发现的东西,但没有一种能够正常工作。无论我做什么,Postgres DB中的条目都是“Null”。这是我的 模式(schema):

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)。所有其他领域都记录得很好。它只是复选框不起作用。

我感谢您提供的任何帮助!

-Brick

1 个答案:

答案 0 :(得分: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_*