[英]Rails scopes - undefined methods
I have a model called "event" that has a scope named "upcoming" wich returns events that are dated in the future. 我有一个名为“event”的模型,其中有一个名为“coming”的范围,它将返回未来日期的事件。 In the rails console, whenever I type 在rails控制台中,每当我键入
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 Yohann
Once you call .all
, @events
is no longer an ActiveRelation
, hence you cannot call a scope on it. 一旦你调用.all
, @events
不再是ActiveRelation
,因此你不能在它上面调用范围。
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. 所以, Event.where(SOME CONDITIONS).order(ORDERING).upcoming.limit(X)
仍然可以工作,但是Event.where(SOME CONDITIONS).order(ORDERING).all.upcoming.limit(X)
不起作用。
You can use scoped
instead of all
to get an active relation object that will allow you to chain scopes on the variable after it's been set: 您可以使用scoped
而不是all
来获取一个活动关系对象,该对象允许您在变量设置后链接范围:
@events = Event.scoped
@events.upcoming
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.