ruby-on-rails - 尝试更新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
解决方案
为什么你觉得"["
在做的时候得到很奇怪User.needs.first
?User.needs
成立text
,示例文本的第一个字符是"["
. 看起来完全正常。
(对我来说)看起来很奇怪的是您使用文本数据类型来存储没有任何序列化的数组。或者,或者,使用本机array
数据类型(如 PostgreSQL)执行以下操作:
t.string 'needs', array: true
...在您的迁移中(有关更多信息,请参阅指南)。
假设数组的默认值似乎是一个哈希(),这似乎也很奇怪(对我来说default: "{}"
)。
我还想知道为什么您不使用模型并在和Need
之间创建 M:M 关系。一些东西,也许,比如:User
Need
# == 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
推荐阅读
- python - 确定值是否在另一个模数的不确定性范围内
- c# - 如果 IHostedService.StopAsync 方法的实现没有响应取消请求会怎样?
- elasticsearch - 跨索引的弹性搜索聚合不起作用
- python - Auth.Token 必须是“用户”实例 Django
- php - 如何在php中分离和修改字符串的内容?
- arrays - 基于键列链接谷歌工作表标签
- excel - 使用 powershell 剪贴板从浏览器中的 excel 复制行
- php - 手动更改状态时不调用订单完成挂钩
- unity3d - 团结 | 具有更好性能的动画
- python - 在 python 上查找奇偶校验异常值,CodeWars 问题