Rails 4: how to access an attribute of an ActiveRecord_Relation-Object?

大城市里の小女人 提交于 2020-01-05 02:44:43

问题


i have a country model and a travel note model. A country has many travel notes and a travel note belongs to one country.

in Rails console:

 TravelNote.published.country(248)

[#<TravelNote id: 172, country_id: 248, status: 1, advice_against: 0, published_at: "2012-10-04 07:57:00", created_at: "2014-09-23 09:09:20", updated_at: "2014-09-23 09:09:20">]

TravelNote.published.country(248).published_at
NameError: undefined local variable or method `published_at' for #<Class:0x00000005a84968>

How can i get the published_at attribute of this object?


回答1:


TravelNote.published.country(248)

returns an array of records, so you have to grab the first item of the array:

TravelNote.published.country(248).first.published_at


来源:https://stackoverflow.com/questions/26483817/rails-4-how-to-access-an-attribute-of-an-activerecord-relation-object

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!