views:

36

answers:

1

I have a model in Rails representing stores

class Store < ActiveRecord::Base

A boolean field "draft" in this model determines if the record is active or if it's just a draft. I'm using acts_as_xapian to do searches in my application and it receives a model where the search should be performed. This part is working. However, I only want to run the search only on items that are active (draft==false)

I'm not sure how I can restrict the search on acts_as_xapian, but I could do the same by creating a new model which contains only the items from the class Store with draft==false.

Initially I thought I could use a method with a find

def self.active
  find :all, :conditions => {:draft => false}
end

but acts_as_xapian really wants a model.

Any suggestions?

+3  A: 

You can create a scope for that to simplify calling it:

named_scope :bloqueado,
  :conditions => { :bloqueado => true }

This means you can call the scope any time you want to find them:

Store.bloqueado.all

From a matter of style, I'd argue that your logic is inverted. Generally it's best to set boolean fields to represent a positive assertion, such as "published" instead of something akin to true meaning "not published" or draft. This gives you the logical pair "published"/"not published" instead of "draft and not published"/"not draft and not not published".

tadman
Sorry, my conditions tag made reference to the :bloqueado field, instead of :draft.I agree with the draft/published argument. Good point.I really need to create a new class for this. It can't look like Store.bloqueado, but rather like ViewableStore.In other words, it needs to pass the test model_class.class == Class
Leo
It is possible to use STI to create two sub-states for a class, like PublishedStore, PreviewStore, both of which inherit from Store. This way you can retrieve, one or the other, and both, if required. Transitioning from one state to another is a bit of a hack, though, as classes aren't generally supposed to transform like that.
tadman
Forgive my ignorance, what's STI?
Leo
STI is "Single Table Inheritance" which lets you define multiple classes in one table. Essentially you create a `type` column as a string, inherit the sub-classes from the parent `Store` and you should be ready to go. There are a lot of questions here that explain, for instance [this one](http://stackoverflow.com/questions/555668/single-table-inheritance-and-where-to-use-it-in-rails).
tadman
Thanks! I think that's exactly the way to go.
Leo