Rails 范围 - 未定义的方法 [英] Rails scopes - undefined methods

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

问题描述

我有一个名为事件"的模型,它有一个名为即将到来"的范围,返回未来日期的事件.在 rails 控制台中,每当我输入

I have a model called "event" that has a scope named "upcoming" wich returns events that are dated in the future. In the rails console, whenever I type

Event.upcoming

它成功返回事件的子集.但是,如果我输入:

It returns the subset of events successfully. However if I type:

@events = Event.all
@events.upcoming

我收到一个未定义的方法即将到来"的错误.作用域仅适用于类而不适用于实例化的变量吗?提前致谢.约翰

I get an undefined method 'upcoming' error. Are scopes only working on the class and not on instantiated variables? Thanks in advance. Yohann

推荐答案

一旦调用 .all@events 就不再是 ActiveRelation>,因此您不能在其上调用作用域.

Once you call .all, @events is no longer an ActiveRelation, hence you cannot call a scope on it.

所以,Event.where(SOME CONDITIONS).order(ORDERING).upcoming.limit(X) 仍然有效,但 Event.where(SOME CONDITIONS).order(ORDERING).all.upcoming.limit(X) 不起作用.

So, Event.where(SOME CONDITIONS).order(ORDERING).upcoming.limit(X) would still work, but Event.where(SOME CONDITIONS).order(ORDERING).all.upcoming.limit(X) would not work.

这篇关于Rails 范围 - 未定义的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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