gpt4 book ai didi

mysql - 在 MySQL Rails 4 中使用数组

转载 作者:行者123 更新时间:2023-11-30 22:00:37 25 4
gpt4 key购买 nike

我正在尝试更改我的“seeker_cvs”表列“location_id”。它是一个整数类型。现在我想把它做成一个数组。 (我被迫在没有多对多关联的情况下做到这一点)。所以我的模型是:

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 Controller 中,我已将许可“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

在 View 中我添加了 multiple: true 到 form:

= 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' }

但是当我尝试创建或更新 seeker_cv(见图)时,我得到:

ActiveRecord::SerializationTypeMismatch at /app/en/seeker_cvs
Attribute was supposed to be a Array, but was a Fixnum. -- 0

Error

附言我需要保存以前创建的 seeker_cvs 和整数类型的 location_id。并且新的或更新的必须具有数组类型的列

最佳答案

问题是 mysql 没有本地数组类型。所以你必须使用 varchar 作为列类型

change_column :seeker_cvs, :location_id, :string

关于mysql - 在 MySQL Rails 4 中使用数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43515521/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com