0
我想改變我的「seeker_cvs」表列「location_id」。這是一個整數類型。現在我想把它作爲一個數組。 (我被迫讓它沒有多對多的關聯)。所以我的模型是:使用MySQL數組Rails 4
class SeekerCv < ActiveRecord::Base
belongs_to :location, class_name: 'Category'
serialize :location_id, Array
end
類別有很多seeker_cvs。
另外我已經添加和運行新的遷移:
class ChangeLocationIdOnSeekerCvs < ActiveRecord::Migration
def change
change_column :seeker_cvs, :location_id, :integer, array: true, default: []
end
end
在seekers_cvs控制器我在許可變更 「LOCATION_ID」 到 「LOCATION_ID:[]」:
class SeekerCvsController < ApplicationController
def new
@cv = SeekerCv.new
end
def create
@cv = SeekerCv.new(cv_params)
@cv.seeker = current_seeker
if @cv.save
redirect_to seeker_cv_path(@cv)
else
render :new
end
end
def edit
@cv = SeekerCv.find(params[:id])
authorize @cv
end
def update
@cv = SeekerCv.find(params[:id])
@cv.attributes = cv_params
if @cv.save
redirect_to seeker_cv_path(@cv)
else
render :edit
end
end
private
def cv_params
params.require(:seeker_cv).permit :name,
:category_id,
:no_experience,
location_id: []
end
end
鑑於我加入multiple: true
形成:
= simple_form_for @cv, html: { class: 'form-horizontal' } do |f|
.panel.panel-default
.panel-heading
h3.panel-title = t('.cv_name')
.panel-body#cv-category
= f.input :name
= f.input :category_id do
= f.select :category_id,
nested_set_options_opt_mod(Category.category.root.children.to_a) { |i| "#{'-' * i.level} #{i.name}" },
{ disabled: Category.category.find_all { |l| !l.leaf? }.map(&:id), include_blank: true },
{ class: 'form-control' }
= f.input :location_id do
= f.select :location_id,
nested_set_options_opt(Category.location.root) { |i| "#{'-' * i.level} #{i.name}" },
{ disabled: Category.location.root.id, include_blank: true },
{ multiple: true, class: 'form-control' }
但是當我triing創建或更新seeker_cv (見圖片),我得到:
ActiveRecord::SerializationTypeMismatch at /app/en/seeker_cvs
Attribute was supposed to be a Array, but was a Fixnum. -- 0
附:我需要保持以前創建的seeker_cvs與整數類型的location_id。新的或更新必須有陣列類型的列
我認爲列的類型必須是一個VARCHAR,因爲MySQL不具備原生數組類型。 – Iceman
'change_column:seeker_cvs,:location_id,:string' – Iceman
冰人,謝謝!您的解決方案很好。現在我已經將我的列更改爲數組類型 –