【问题标题】:Array field not being recognized as attribute数组字段未被识别为属性
【发布时间】:2013-07-18 18:17:20
【问题描述】:

我创建了以下模型,

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

我还在我的 Gemfile 中添加了 pg 数组解析器 gem。

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

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.

【问题讨论】:

  • 你检查过你在 PostgreSQL 中的users 表吗?来自psql 的简单\d users 将告诉您该表的真实外观。
  • 我在schema.rb 中没有看到类别字段,所以我重置了数据库。结果显示在答案中。
  • 您是否尝试过 default: []default: "'{}'::integer[]"? The old postgres_ext gem for Rails3 properly casts '{}'` 到 '{}'::integer[] 但也许 Rails4 变得混乱并改为使用 '{}'.to_i
  • 谢谢@mu。使用default: [] 有效。发布它作为答案,我会给你信用。

标签: ruby-on-rails arrays postgresql attributes ruby-on-rails-4


【解决方案1】:

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

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

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

这将触发postgres_ext 的正确to-sql-ification,因此它也应该在Rails4 中做正确的事情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2010-11-27
    • 2018-10-28
    • 1970-01-01
    • 2018-11-08
    • 1970-01-01
    • 2011-06-09
    • 2021-03-23
    • 2022-11-20
    相关资源
    最近更新 更多