简体   繁体   English

如何在Rails中应用此过滤器

[英]How to apply this filter in Rails

I have a table called as language which has a column called as lang_code. 我有一个称为language的表,该表有一个称为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. 我需要从此表中删除3种语言(CHI,DAN ad VIE)。 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? 如何在Rails中做到这一点?

Thanks 谢谢

Use default_scope : 使用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. 您创建一个迁移,在其中添加:active列。 You set a default (EG default is active) 设置默认值(EG默认值处于活动状态)

  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. 在同一迁移中(请谨慎调用Language.reset_column_information)或在另一迁移中,您要处理与(CHI,DAN,VIE)有关的任何数据库关系。 Then, you inactivate them (inactive = true) 然后,您将它们停用(无效= true)

  3. In the Language class, you use a default_scope: 在Language类中,使用default_scope:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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