首页 > 解决方案 > 尝试更新rails列数组类型时出现奇怪的格式

问题描述

我正在尝试更新一个名为需求的列,如下所示:

t.text "needs", default: "{}"

我经历了几次迁移以尝试使其正常工作,但仍然遇到相同的错误。它不会更新列,看起来它重新格式化了我的 api 调用中的数据。这是我从 Rails 服务器得到的:

Parameters: {"user"=>{"birthdate"=>"2019-07-30T11:59:31.215Z", "needs"=>["relationship", "life", "general"], "coach_gender"=>""}, "id"=>"15"}

UPDATE "users" SET "needs" = $1, "updated_at" = $2 WHERE "users"."id" = $3  [["needs", "[\"relationship\", \"life\", \"general\"]"], ["updated_at", "2019-07-30 12:08:12.013589"], ["id", 15]]

然后,当我尝试从用户那里获得第一个需求时,如下所示:

User.needs.first

我明白了

"["

我的控制器如下所示:

def edit
  User.find_by(id: params[:id]).update_attributes(user_params)
end

def user_params
  params.require(:user).permit(:first_name, :last_name, :birthdate, :description, :email, :password, :coach_gender, :needs => [])
end

标签: ruby-on-railsrubypostgresql

解决方案


为什么你觉得"["在做的时候得到很奇怪User.needs.firstUser.needs成立text,示例文本的第一个字符是"[". 看起来完全正常。

(对我来说)看起来很奇怪的是您使用文本数据类型来存储没有任何序列化的数组。或者,或者,使用本机array数据类型(如 PostgreSQL)执行以下操作:

t.string 'needs', array: true

...在您的迁移中(有关更多信息,请参阅指南)。

假设数组的默认值似乎是一个哈希(),这似乎也很奇怪(对我来说default: "{}")。

我还想知道为什么您不使用模型并在和Need之间创建 M:M 关系。一些东西,也许,比如:UserNeed

# == Schema Information
#
# Table name: needs
#
#  id               :bigint           not null, primary key
#  name             :string
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#
class Need < ApplicationRecord
  has_many :user_needs
  has_many :users, through: :user_needs
end

# == Schema Information
#
# Table name: user_needs
#
#  id               :bigint           not null, primary key
#  user_id          :integer
#  need_id          :integer
#  created_at       :datetime         not null
#  updated_at       :datetime         not null
#
class UserNeed < ApplicationRecord
  belongs_to :user
  belongs_to :need
end

class User < ApplicationRecord
  has_many :user_needs
  has_many :needs, through: :user_needs
end

这将使查询更容易。比如,“给我所有有生活需要的用户”可能是这样的:

Need.find_by(name: 'life').users

推荐阅读