开发者

Smart Filtering with Rails ActiveRecord

Lets assume that i have an AR model Foo

Foo.find methods will r开发者_运维问答eturn all entries from the foo table based on the criteria.. What i need is to have some kind of default criteria like country column so that if i define this somehow in AR, all my Foo.find methods will return entries only from that country...

How can i tell AR to use such default behaviour or set it dynamically?


Well, I think you are talking about overriding the find functionality, which is probably not that safe, but do-able. You'll run into issues with supporting the different find formats as well. For example, how will you handle Foo.find(1) and Foo.find([1,2,3])? To do this in a safe way you should really use scopes. For example, in Rails 3 you would do the following:

class Foo
  scope :country, lambda{ |country| where(country: country) }
end

You could then use this scope anytime you make a call to query Foo. For example:

Foo.country('United States').where(...).all

If you wanted to simplify this code further because you used it a lot, you could create a function on Foo to deal with this as well:

class Foo
  def self.with_country
    country(current_selected_country)
  end
end

So that you could make find calls like this:

Food.with_country.all

By using this method you avoid having to override default ActiveRecord functionality, so your code is easier for other developers to understand and you don't have to worry about supporting a bunch of different method formats and calls.

If you do want this to be your default behavior, you can use the ActiveRecord default_scope like this:

class Foo
  default_scope where(country: 'United States')
end

This will be applied when creating a record, but not when updating a record.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜