本地控制台上的 ActiveRecord 不工作,但与 Heroku 一起工作

ActiveRecord on local console not working, but works with Heroku

我现在很困惑。

我有一个充满机场数据的数据库。我试图从我的控制台中的不同记录中调用某些属性,但它不起作用。奇怪的是,它在我的 heroku 控制台中运行良好。例如:

如果我输入:x = Airport.where(代码:"JFK")。当我在我的控制台中输入 "x" 时,我得到了 JFK 的完整记录。但是,当我键入 x.runway_length 时,出现方法错误。

奇怪的是,当我在 Heroku 控制台中执行相同的过程时,我将获得跑道长度(或附加到 "x" 的任何其他属性)。

这是怎么回事?我是不是漏了什么。

谢谢!

x = Airport.where(代码:"LAX")

Airport Load (2.9ms)  SELECT "airports".* FROM "airports" WHERE "airports"."code" = 'LAX'
=> #<ActiveRecord::Relation [#<Airport id: 3533, code: "LAX", lat: 33.9456, lon: -118.391, name: "Los Angeles International Airport", city: "Los Angeles", state: "California", country: "United States", woeid: 12520706, tz: "America/Los_Angeles", phone: "", email: "", url: "", runway_length: 12091, elev: 126, icao: "KLAX", direct_flights: 200, carriers: 99, created_at: "2015-08-06 19:10:03", updated_at: "2015-08-17 03:05:53", current_high_temp: 84, current_low_temp: 70>]>

现在,当我尝试时:x.current_high_temp

NoMethodError: undefined method `current_high_temp' for #<ActiveRecord::Relation::ActiveRecord_Relation_Airport:0x007fd89ed33b18>

'Where' returns 一个数组,你正在调用它的实例方法。

尝试

x = Airport.where(code: "LAX").first

问题是你使用的方法。

Model#where 不是 return 一个对象(正如活动记录所预期的那样)供您使用,您应该使用 Model#find_by(attribute: expression)

在你的情况下使用:

x = Airport.find_by(code: "LAX")
where(opts = :chain, *rest) public

Returns一个新的关系,它是根据参数中的条件过滤当前关系的结果。

x = Airport.where(code: "LAX")

Airport Load (2.9ms)  SELECT "airports".* FROM "airports" WHERE "airports"."code" = 'LAX'
=> #<ActiveRecord::Relation [#<Airport id: 3533, code: "LAX", lat: 33.9456, lon: -118.391, name: "Los Angeles International Airport", city: "Los Angeles", state: "California", country: "United States", woeid: 12520706, tz: "America/Los_Angeles", phone: "", email: "", url: "", runway_length: 12091, elev: 126, icao: "KLAX", direct_flights: 200, carriers: 99, created_at: "2015-08-06 19:10:03", updated_at: "2015-08-17 03:05:53", current_high_temp: 84, current_low_temp: 70>]>

您注意到对象类型是 ActiveRecord::Relation 而不是 Airport 并且 Airport 对象用数组文字包装 [] 但是,集合类型不是数组.所以,
要么你想使用

x = Airport.where(code: "LAX").first
or 
x = Airport.where(code: "LAX")[0] # not recommended

如果 'code' 是您可以使用的唯一键

# this gives the first airport with code = 'LAX'
x = Airport.find_by_code("LAX")

或者,如果您想查看所有机场的 current_high_temp,那么您可能需要这样做

x = Airport.where(code: "LAX").pluck('current_high_temp')

pluck(*column_names) public Use pluck as a shortcut to select one or more attributes without loading a bunch of records just to grab the attributes you want.

Person.pluck(:name) instead of Person.all.map(&:name)