NoMethodError: undefined method `created_at' for in Rails

佐手、 提交于 2019-12-24 05:54:23

问题


So here is a object I retrieved from the ActiveRecord other = [#<Referrer id: 16, name: "Other", published: true, created_at: "2011-07-11 16:22:00", updated_at: "2011-07-11 16:22:00">] Why can't I do other.created_at while I can do other.name?

Here is the model:

class Referrer < ActiveRecord::Base
end

The error I'm getting:

NoMethodError: undefined method `created_at' for #<ActiveRecord::Relation:0x1035763c8>

What have I missed?


回答1:


If you'll notice, other is actually an ActiveRecord::Relation which basically means it's acting like an array of Referrer objects. So you can't just call created_at on it. You could call other.first.created_at or if you want an array of created_at dates you could do other.map(&:created_at).

The reason you can call other.name is because an ActiveRecord::Relation responds to name. But it's a different name method than the name attribute on your Referrer model. other.name should return "Referrer" instead of "Other" right?



来源:https://stackoverflow.com/questions/6653779/nomethoderror-undefined-method-created-at-for-in-rails

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