Rails 3.0 中的多个范围
我是 Rails 的初学者,我对范围有疑问。
我的课程有 2 个作用域:
class Event < ActiveRecord::Base
belongs_to :continent
belongs_to :event_type
scope :continent, lambda { |continent|
return if continent.blank?
composed_scope = self.scoped
composed_scope = composed_scope.where('continent_id IN ( ? )', continent).all
return composed_scope
}
scope :event_type, lambda { |eventType|
return if eventType.blank?
composed_scope = self.scoped
composed_scope = composed_scope.where('event_type_id IN ( ? )', eventType).all
return composed_scope
}
end
在我的控制器中,我想同时使用这 2 个作用域。我做到了:
def filter
@event = Event.scoped
@event = @event.continent(params[:continents]) unless params[:continents].blank?
@event = @event.event_type(params[:event_type]) unless params[:event_type].blank?
respond_with(@event)
end
但我不起作用,我有这个错误:
undefined method `event_type' for #<Array:0x7f11248cca80>
这是因为第一个作用域返回一个数组。
我该怎么做才能让它发挥作用?
谢谢 !
I am a beginner in Rails and i have a problem with scope.
I have my class with 2 scopes :
class Event < ActiveRecord::Base
belongs_to :continent
belongs_to :event_type
scope :continent, lambda { |continent|
return if continent.blank?
composed_scope = self.scoped
composed_scope = composed_scope.where('continent_id IN ( ? )', continent).all
return composed_scope
}
scope :event_type, lambda { |eventType|
return if eventType.blank?
composed_scope = self.scoped
composed_scope = composed_scope.where('event_type_id IN ( ? )', eventType).all
return composed_scope
}
end
And in my controller i want to use this 2 scopes at the same time. I did :
def filter
@event = Event.scoped
@event = @event.continent(params[:continents]) unless params[:continents].blank?
@event = @event.event_type(params[:event_type]) unless params[:event_type].blank?
respond_with(@event)
end
But i doesn't work, I have this error :
undefined method `event_type' for #<Array:0x7f11248cca80>
It's because the first scope return an array.
How can I do to make it work?
Thank you !
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不应该在作用域中附加“.all”:
它通过触发 SQL 查询将可链接的 ActiveRelation 转换为数组。
所以只需将其删除即可。
奖励:
一些重构:
You should not append '.all' in your scopes:
It transforms a chainable ActiveRelation into an Array, by triggering the SQL query.
So simply remove it.
Bonus:
Some refactoring:
我认为你不需要在你的范围内使用 .scoped 。
在上面的代码中,您已经将所有内容返回为“范围”。
另外,您的范围不需要“除非”,因为只有当您的参数不为空时才会调用它们。所以你的作用域可能会变成这样
,或者以更多 Rails 3 的方式,
这要短得多:)
I don't think you need .scoped in your scopes.
on the code above you already have everything returning as 'scoped'.
Plus, your scopes wouldnt need an 'unless' on them, since they will only be called if your params arent blank. So your scopes could become something like this
or, on a more Rails 3 way,
which is much shorter :)