views:

42

answers:

2

Hi,

I have a table called as language which has a column called as lang_code. It has the following values.

id  lang_code  created_at           updated_at
1   ARA        2010-07-29 15:27:25  NULL
2   CHI        2010-07-29 15:27:25  NULL
3   DAN        2010-07-29 15:27:25  NULL
4   DEU        2010-07-29 15:27:25  NULL
5   ESP        2010-07-29 15:27:25  NULL
6   KOR        2010-07-29 15:27:25  NULL
7   VIE        2010-07-29 15:27:25  NULL

I have a requirement to remove 3 languages (CHI, DAN ad VIE) from this table. I can simply write a migration and remove the values permanently from the table. But I do not want to do that. Instead, I want to filter them out in the model level so that any operation that I do on this particular model should not have these three languages in it. How to do that in Rails?

Thanks

+3  A: 

Use default_scope:

class Language < ActiveRecord::Base
  UNWANTED_LANGUAGES = ["CHI", "DAN", "VIE"]
  default_scope :conditions => ["lang_code not in (?)", UNWANTED_LANGUAGES]
  ...
end
neutrino
SWEEEEEEEEEEEEET!! thanks!!!
Bragboy
A: 
  1. You create a migration where you add an :active column. You set a default (EG default is active)

  2. In the same migration(be carefull to call Language.reset_column_information) or in another migration, you take care of any DB relations with (CHI, DAN, VIE) involved. Then, you inactivate them (inactive = true)

  3. In the Language class, you use a default_scope:

    default_scope :conditions => { :active => true }

Vlad Zloteanu
This way, you can activate/deactivate languages from an admin interface.
Vlad Zloteanu