问题
I'm trying to store an array (:vehicles) in my database. This array consists of 3 possible vehicles that the user selects with checkboxes.
<% @vehicles.each_with_index do |vehicle,index| %>
    <label>
      <div >
        <%= check_box_tag "vehicles[]", index ,class: "available" ,style: "display:none" %>
        <%= vehicle %>
      </div>
    </label>
<%end %>
The ':vehicles' attribute type is 'text' and I used this code to make it an array:
serialize :vehicles, Array
If I send the params it gets these values in an array.
"vehicles"=>["0", "1", "2"],
"commit"=>"Sign up!", 
"controller"=>"registrations", 
"action"=>"create"
The problem is that this array isn't stored in the database when I try save it. In the database the code looks like this:
vehicles: []
Controller code:
 def create
    @student = Student.create(student_params)
    if @student.save!
      redirect_to @student
    else
      render :new
    end
  end
Student params:
def student_params
    params.require(:student).permit(availabilities_attributes: [ :id, :day, :available])
  end
Anyone have an idea how to get those values into this array?
Thanks!
回答1:
In your strong parameters you are going to have to permit the :vehicles attribute as an array, like this:  vehicles: []
I'm not sure what version of Devise you are using, but drawing from their documentation, in the "strong parameters" section, you could permit vehicles like this in the application controller:
def configure_permitted_parameters
  devise_parameter_sanitizer.permit(:sign_up) do |student_params|
    student_params.permit({ vehicles: [] }, :email, :password, :password_confirmation)
  end
end
Also if you are using Postgres database, I recommend setting up your vehicles attribute to receive an array directly in the database.  You can do so with a migration like this:
class AddArrayToStudents < ActiveRecord::Migration
  def change
    add_column :students, :vehicles, :string, array: true, default: []
  end
end
    来源:https://stackoverflow.com/questions/39881222/array-isnt-persisted-to-database