如何使 Rails 3 动态范围有条件? [英] How to make a Rails 3 Dynamic Scope Conditional?

查看:30
本文介绍了如何使 Rails 3 动态范围有条件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在 rails 3 中创建一个以传入参数为条件的动态命名范围.例如:

I'd like to make a dynamic named scope in rails 3 conditional on the arguments passed in. For example:

class Message < AR::Base
  scope :by_users, lambda {|user_ids| where(:user_id => user_ids) }
end

Message.by_users(user_ids)

但是,即使使用空的 user_id 数组,我也希望能够调用此范围,并且在这种情况下不应用 where.我想在范围内执行此操作的原因是我要将其中的几个链接在一起.

However, I'd like to be able to call this scope even with an empty array of user_ids, and in that case not apply the where. The reason I want to do this inside the scope is I'm going to be chaining several of these together.

我该如何进行这项工作?

How do I make this work?

推荐答案

要回答您的问题,您可以:

To answer your question you can do:

scope :by_users, lambda {|user_ids| 
  where(:user_id => user_ids) unless user_ids.empty?
}

不过

我通常只使用 scope 进行简单的操作(为了可读性和可维护性),之后的任何操作,我只使用类方法,例如:

I normally just use scope for simple operations(for readability and maintainability), anything after that and I just use class methods, so something like:

class Message < ActiveRecord::Base

  def self.by_users(users_id)
    if user_ids.empty?
      scoped
    else
      where(:user_id => users_id)
    end
  end

end

这将适用于 Rails 3,因为 where 实际上返回一个 ActiveRecord::Relation,您可以在其中链接更多查询.

This will work in Rails 3 because where actually returns an ActiveRecord::Relation, in which you can chain more queries.

我也在使用 #scoped,它将返回一个匿名范围,允许您链接查询.

I'm also using #scoped, which will return an anonymous scope, which will allow you to chain queries.

最后,这取决于你.我只是给你选择.

In the end, it is up to you. I'm just giving you options.

这篇关于如何使 Rails 3 动态范围有条件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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