简体   繁体   中英

How to apply this filter in Rails

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

Use default_scope :

class Language < ActiveRecord::Base
  UNWANTED_LANGUAGES = ["CHI", "DAN", "VIE"]
  default_scope :conditions => ["lang_code not in (?)", UNWANTED_LANGUAGES]
  ...
end
  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 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM