带有Postgres的Rails为具有值的列返回nil

时间:2015-03-07 23:51:08

标签: ruby-on-rails ruby postgresql activerecord

我在schema.rb中声明了这个模型:

create_table "lot_reports", force: :cascade do |t|
  t.integer  "spaces_occupied"
  t.integer  "spaces_newly_occupied"
  t.string   "name"
  t.time     "time_stamp"
  t.datetime "created_at",            null: false
  t.datetime "updated_at",            null: false
  t.integer  "lot_id"
end

当我尝试访问模型上的spaces_occupied属性时,即使数据库显示该字段的值,我也会收到nil

LotReport Load (0.5ms)  SELECT  "lot_reports".* FROM "lot_reports"  ORDER BY "lot_reports"."id" ASC LIMIT 1
#=> #<LotReport id: 1, spaces_occupied: 107, spaces_newly_occupied: 153, name: "Cummerata Field", time_stamp: "2000-01-01 23:13:25", created_at: "2015-03-07 23:19:42", updated_at: "2015-03-07 23:19:42", lot_id: 1> 
LotReport.first.spaces_occupied
LotReport Load (0.5ms)  SELECT  "lot_reports".* FROM "lot_reports"  ORDER BY "lot_reports"."id" ASC LIMIT 1
#=> nil

不确定这里发生了什么。这是唯一存在此问题的属性;其他人回归我的期望。

编辑:这是LotReport源代码

class LotReport < ActiveRecord::Base
   belongs_to :lot

   def plot_array
    [spaces_occupied, time_stamp]
   end
end

1 个答案:

答案 0 :(得分:1)

这是一种诊断它的方法......

请在您的问题中添加型号代码,例如:

$ cat app/models/lot_report.rb

如果您将正在使用的版本添加到您的问题中,它可能会有所帮助,例如:

$ uname -a

$ bin/rails --version

$ bundle exec gem list pg

当您按ID要求记录时,您会得到什么确切的输出,并尝试更改提交的文件?

$ bin/rails console
> lot = LotReport.find(1)
> p lot.spaces_occupied
> lot.spaces_occupied = 1234
> p lot.spaces_occupied
> lot.save!
> p lot.spaces_occupied
> lot.reload
> p lot.spaces_occupied