NoMethodError:未定义的方法`created_at'属性的Rails中 [英] NoMethodError: undefined method `created_at' for in Rails

查看:96
本文介绍了NoMethodError:未定义的方法`created_at'属性的Rails中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

因此​​,这里是我的ActiveRecord的检索的对象其它= [#<推荐人ID:16,店名:其他,发表:真的,created_at:2011-07-11 16: 22:00的updated_at:2011-07-11 16时22分00秒>] 我为什么不能做 other.created_at ,而我能做的 other.name

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?

下面是模型:

class Referrer < ActiveRecord::Base
end

我收到的错误:

The error I'm getting:

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

我有什么遗漏?

What have I missed?

推荐答案

如果你会发现,实际上是一个的ActiveRecord ::关系这基本上意味着它的作用就像引荐对象的数组。所以你不能只是叫 created_at 就可以了。你可以称之为 other.first.created_at 或者如果你想 created_at 的数组日期,你可以做 other.map(安培;:created_at)

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).

您可以致电 other.name 的原因是因为的ActiveRecord ::关联响应名。但它是一个不同的名称方法比你的推荐人的名称属性模式。 other.name 应该返回推荐人而不是其他吧?

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?

这篇关于NoMethodError:未定义的方法`created_at'属性的Rails中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆