问题
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