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) }
这要短得多:)
- 如何通过Ruby on Rails中的营销电子邮件api在sendgrid中获取可用的电子邮件配额
- ImageMagick:这个convert-command在做什么?
- 在rails app中为内置类添加方法
- ruby将换行符写入文件但不解释为真正的换行符
- 在不使用外部gem的情况下将文件上传到db Rails 3
- ActiveModel :: MissingAttributeError:无法写入未知属性`user_id`
- Ruby守护进程和JRuby – 替代选项
- 当你没有在ruby中指定exception类时,你会遇到哪些exception?
- 在mongoid db中采用vs distinct。 哪个更快?