数组不会持久保存到数据库

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

   

‘: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 

任何人都知道如何将这些值放入此数组中?

谢谢!

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

我不确定您使用的Devise版本是什么,但是根据他们的文档 ,在“强参数”部分中,您可以在应用程序控制器中允许这样的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