gpt4 book ai didi

ruby-on-rails - 数组字段未被识别为属性

转载 作者:行者123 更新时间:2023-11-29 11:40:45 25 4
gpt4 key购买 nike

我创建了以下模型,

class CreateUsers < ActiveRecord::Migration
def change
create_table :users do |t|
t.string :name
t.string :email
t.string :password_digest
t.string :location_type
t.integer :location_id
t.integer :categories, array: true, default: '{}'

t.timestamps
end
add_index :user, :email, unique: true
end
end

我还将 pg 数组解析器 gem 添加到我的 Gemfile 中。

问题是每当我创建用户时,它都会告诉我类别是一个未知属性。

User.create(name: "Bob", email: "bob@gmail.com", 
password: "password", password_confirmation: "password", categories: [1, 2])

The Error:

unknown attribute: categories

出了什么问题,我该如何解决?

更新:

运行 rake db:drop db:create db:migrate 后,我遇到了这个新错误。

PG::Error: ERROR:  column "categories" is of type integer[] but default expression is of type integer
HINT: You will need to rewrite or cast the expression.

最佳答案

postgres_ext用于向 Rails3 添加数组支持的 gem 理解 default: '{}' 意味着 SQL 应该说 '{}'::integer[] 但我猜Rails4 驱动程序变得有点困惑并说 '{}'.to_i 或类似的东西;抱歉,我没有在任何地方设置 Rails4,所以我不能说得更具体,但它确实符合您看到的错误。

您可以尝试使用 Ruby 数组而不是 PostgreSQL 风格的数组字符串:

t.integer :categories, array: true, default: []

这将通过 postgres_ext 触发正确的 SQL 化,因此它也应该在 Rails4 中做正确的事。

关于ruby-on-rails - 数组字段未被识别为属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17731057/

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