Rails 3.0中的多个范围 [英] Multiple scope in rails 3.0

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

问题描述

我是Rails的初学者,我对范围有疑问.

I am a beginner in Rails and i have a problem with scope.

我的课有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
   }

结束

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

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.

如何使它正常工作?

谢谢!

推荐答案

您不应在范围内附加".all":

You should not append '.all' in your scopes:

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

It transforms a chainable ActiveRelation into an Array, by triggering the SQL query.

因此只需将其删除.

奖金:

一些重构:

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

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

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