在Ruby on Rails中,为什么story.votes会返回一个空的Array对象,但story.votes.create实际上会调用Vote类的方法?

发布于 2024-09-02 18:35:28 字数 448 浏览 2 评论 0原文

在 Ruby on Rails 中,假设一个 Story 对象可以“has_many”投票对象(一个故事被许多用户评为“热门”)。

因此,当我们执行

s = Story.find(:first)

s 时,它是一个 Story 对象,并说

s.votes

返回 []

s.votes.class

返回 Array

很明显,s.votes 是一个空的 Array 对象。

这时候

s.votes.create

调用的时候,其实是调用了Vote类的一个方法?为什么 Array 类对象可以调用 Vote 类方法?

In Ruby on Rails, say a Story object can "has_many" Vote objects (a story is voted "hot" by many users).

So when we do a

s = Story.find(:first)

s is a Story object, and say

s.votes

returns []
and

s.votes.class

returns Array

So clearly, s.votes is an empty Array object.

At this time, when

s.votes.create

is called, it actually invokes a method of the Vote class? How come an Array class object can invoke a Vote class method?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

蓝眼泪 2024-09-09 18:35:28

在您的情况下,.votes返回Array,它返回一个特殊的Association对象。

它看起来像 Array 的原因是因为关联对象将其所有方法(除了 create 等动态方法之外)委托给它内部保存的数组对象。而且,这意味着当您在对象上调用 .class 时,also 也会被委托给 Array 对象。

In your case, .votes is not returning an Array, it's returning a special Association object.

The reason it looks like an Array is because the association object delegates all of its methods except for the dynamic ones like create to an array object it holds internally. And, this means that when you call .class on the object, that also gets delegated to the Array object.

奢欲 2024-09-09 18:35:28

votes 不是一个数组,它是一个 Story 对象的方法。如果您单独调用它,它会返回与该 Story 关联的所有 Vote 记录的数组。当您执行 s.votes.class 时,您得到 Array 的原因是 s.votes 返回一个数组(在本例中为空,因为 s 没有投票)并且您正在检查返回数组的类。

反过来,s.votes.create 是 Rails 根据模型关联动态生成的另一种方法。它不是Array的方法。

votes is not an array, it's a method of a Story object. If you call it alone, it returns an array of all Vote records associated with that Story. The reason you are given Array when you do s.votes.class is that s.votes is returning an array (which in this case is empty because s has no votes) and you're checking the class of the returned array.

In turn, s.votes.create is another method dynamically generated by Rails based on your model associations. It's not a method of Array.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文