为什么即使分配了默认的mysql值,布尔属性也保存为null

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了为什么即使分配了默认的mysql值,布尔属性也保存为null相关的知识,希望对你有一定的参考价值。

这必须是一个直截了当的错误,但我无法确定其发生的原因。我已经从之前的问题改变了我的帖子,我没有真正从我的项目中准确发布。对于那些可能已经看过上一个的人来说,这是一个更好的帖子。基本上,我有两个布尔值,:accepted:complete。我已经分配了默认的:accepted => true:complete => false,但是当我创建一个新的:accept对象时,它们仍然保存为null。文件:

accepts_controller.rb(create和params)

def create
  @self_delivery = SelfDelivery.find_by(
    id: params[:self_delivery_id])

  begin
    @accept = Accept.create(
      :user_id => current_user.id,
      :self_delivery_id => @self_delivery.id,
      :accepted => params[:accepted],
      :complete => params[:complete])

  rescue ActiveRecord::RecordNotUnique => e
    flash[:notice]= 'Duplicate Record'
  end

  if @accept.save!
    redirect_to accept_path(@accept)
    flash[:notice]= 'Accept was successfully created.'
  end
end

new.html.erb

<h1>New Accept</h1>

<%= form_with(model: @accept, url: self_delivery_accepts_path(:user_id => params[:user_id], :self_delivery_id => params[:self_delivery_id]), :method => :post) do |form| %>
<% if @accept.errors.any? %>
<div id="error_explanation">
  <h2><%= pluralize(@accept.errors.count, "error") %> prohibited this accept from being saved:</h2>

  <ul>
  <% @accept.errors.full_messages.each do |message| %>
    <li><%= message %></li>
  <% end %>
  </ul>
 </div>
<% end %>

<div class="field">
<%= form.label :accepted %>
<%= form.check_box :accepted, checked: true %>
</div>

<div class="field">
<%= form.label :complete %>
<%= form.check_box :complete, checked: true %>
</div>

<div class="actions">
<%= form.submit %>
</div>
<% end %>


<%= link_to 'Back', self_delivery_accepts_path(:self_delivery_id => params[:self_delivery_id], :accepted => params[:accepted], :complete => params[:complete]) %>

把params.inspect

<ActionController::Parameters {"utf8"=>"✓", "authenticity_token"=>"ANOwCS3enYdqqcN01iAJg7EgRDhAC/Gpb3/h6yCGz2qSrKEz874ANBYeKGQuKSc3ctopIixI4rKiKuC5FJdsnQ==", "accept"=>{"accepted"=>"1", "complete"=>"0"}, "commit"=>"Create Accept", "controller"=>"accepts", "action"=>"create", "self_delivery_id"=>"1"} permitted: false>
答案

这就是前端的参数:

..., "accept"=>{"accepted"=>"1", "complete"=>"0"}, ...

在你的代码中你应该尊重这种格式:

:accepted => params['accept']['accepted'],
:complete => params['accept']['complete']

以上是关于为什么即使分配了默认的mysql值,布尔属性也保存为null的主要内容,如果未能解决你的问题,请参考以下文章

AngularJS:如何在为缺少的属性提供默认值时避免非分配错误?

mysql 数据库中的布尔字段

从 UserDefaults 获得的布尔值打印为 0 或 1,即使保存为 Any

Java 的布尔默认值是“真”吗? [复制]

即使在 Android 中更改后,通知声音也不会从默认值更改

mysql怎么获取数据表字段enum类型的默认值