【问题标题】:Array isn't persisted to database数组未持久化到数据库
【发布时间】:2016-10-05 18:26:08
【问题描述】:

我正在尝试在我的数据库中存储一个数组 (:vehicles)。该数组由用户使用复选框选择的 3 种可能的车辆组成。

<% @vehicles.each_with_index do |vehicle,index| %>
    <label>
      <div >
        <%= check_box_tag "vehicles[]", index ,class: "available" ,style: "display:none" %>
        <%= vehicle %>
      </div>
    </label>
<%end %>

':vehicles' 属性类型是'text',我用这段代码将它变成了一个数组:

serialize :vehicles, Array

如果我发送参数,它会在数组中获取这些值。

"vehicles"=>["0", "1", "2"],
"commit"=>"Sign up!", 
"controller"=>"registrations", 
"action"=>"create"

问题是当我尝试保存该数组时,它没有存储在数据库中。在数据库中,代码如下所示:

vehicles: []

控制器代码:

 def create
    @student = Student.create(student_params)
    if @student.save!
      redirect_to @student
    else
      render :new
    end
  end

学生参数:

def student_params
    params.require(:student).permit(availabilities_attributes: [ :id, :day, :available])
  end

有人知道如何将这些值放入这个数组吗?

谢谢!

【问题讨论】:

  • 您是否允许在您的控制器强参数中使用车辆数组属性?
  • 发布您的创建操作
  • @Ren 是的,def configure_permitted_parameters devise_parameter_sanitizer.for(:sign_up) &lt;&lt; [:vehicles] end
  • 请不要在 cmets 中发布代码。太难读了。而是更新您的原始帖子。
  • 为什么不使用ARRAY 类型的列来存储这些数据? Postgres 支持它,这太棒了。

标签: ruby-on-rails arrays postgresql devise params


【解决方案1】:

在您的强参数中,您将不得不允许 :vehicles 属性作为数组,如下所示:vehicles: []

我不确定您使用的是什么版本的 Devise,但从他们的 documentation 中提取,在“强参数”部分,您可以在应用程序控制器中允许 vehicles 像这样:

def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up) do |student_params|
    student_params.permit({ vehicles: [] }, :email, :password, :password_confirmation)
  end
end

另外,如果您使用 Postgres 数据库,我建议您设置 vehicles 属性以直接在数据库中接收数组。您可以通过这样的迁移来做到这一点:

class AddArrayToStudents < ActiveRecord::Migration
  def change
    add_column :students, :vehicles, :string, array: true, default: []
  end
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-19
    • 2021-09-19
    • 2017-08-09
    相关资源
    最近更新 更多