【问题标题】:Multiple scope in rails 3.0rails 3.0中的多个范围
【发布时间】:2011-10-23 20:48:18
【问题描述】:

我是 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
   }

结束

在我的控制器中,我想同时使用这 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>

这是因为第一个作用域返回一个数组。

我该怎么做才能让它发挥作用?

谢谢!

【问题讨论】:

    标签: ruby-on-rails ruby ruby-on-rails-3 scopes


    【解决方案1】:

    您不应在作用域中附加“.all”:

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

    所以简单地删除它。

    奖金:

    一些重构:

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

    【讨论】:

      【解决方案2】:

      我认为您的作用域中不需要 .scoped。

      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)
      }
      

      这要短得多:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-10-11
        • 2015-02-14
        • 2014-08-26
        • 2021-07-02
        • 2016-12-29
        • 2013-08-14
        相关资源
        最近更新 更多