本地控制台上的ActiveRecord无法正常工作,但与Heroku一起使用

时间:2015-08-18 21:37:42

标签: ruby-on-rails activerecord heroku rails-console

我现在很困惑。

我有一个装满机场数据的数据库。我试图在我的控制台中调用来自不同记录的某些属性,但它不起作用。奇怪的是,它在我的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>

3 个答案:

答案 0 :(得分:1)

'Where'返回一个数组,并在其上调用实例方法。

尝试

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

答案 1 :(得分:0)

问题在于您使用的方法。

Model#where不会返回一个对象(正如预期的活动记录所示),您可以使用Model#find_by(attribute: expression)

在您的情况下使用:

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

答案 2 :(得分:0)

where(opts = :chain, *rest) public

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

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而不是AirportAirport对象包含数组文字[]但是,集合类型不是数组。所以,
你想要使用

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使用pluck作为选择一个或的快捷方式   没有加载一堆记录的更多属性只是为了抓住   你想要的属性。

     

Person.pluck(:name)   代替   Person.all.map(&:name)

相关问题