rails 3.0中的多个范围

我是Rails的初学者,我的范围有问题。

我的课程有两个范围:

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 } 

结束

在我的控制器中,我想同时使用这两个示波器。 我做了:

 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 # 

这是因为第一个范围返回一个数组。

我怎样才能使它工作?

谢谢 !

你不应该在你的范围中附加’.all’:

它通过触发SQL查询将可链接的ActiveRelation转换为Array。

所以只需删除它。

奖金:

一些重构:

 scope :continent, lambda { |continent| self.scoped.where('continent_id IN ( ? )', continent) unless continent.blank? } 

我不认为你需要。在你的范围内。

 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 

在上面的代码中,您已经将所有内容都返回为“作用域”。 另外,你的范围不需要’除非’,因为只有当你的参数不是空白时它们才会被调用。 所以你的范围可能会变成这样的东西

 scope :continent, lambda { |continent| where('continent_id IN ( ? )', continent) } 

或者,在更多的Rails 3方式上,

 scope :continent, lambda { |continent_id| where(:continent_id => continent_id) } 

这要短得多:)