如何在初始化器中添加除外?

时间:2015-01-08 11:28:38

标签: ruby ruby-on-rails-3 strong-parameters

我在rails项目中使用了strong_parameters gem。要将其应用于我创建了初始化程序的所有模型,并将下面的代码放入其中。

 ActiveRecord::Base.send(:include, ActiveModel::ForbiddenAttributesProtection)

现在我不想将它应用于一个名为投票的模型。请帮我排除那个模型?

1 个答案:

答案 0 :(得分:0)

我建议您为所需的每个型号添加module。你正在做的是修补ActiveRecord,这不是一个好主意。

<强>更新

这是一个解决方案,您只能为自己喜欢的模型添加ActiveModel::ForbiddenAttributesProtection。将代码放在初始化程序中。

all_models = Dir["#{Rails.root}/app/models/**/*.rb"].map do |filename| 
  filename[/(?<=models\/).*(?=\.rb)/].camelize.constantize
end

models_without_forbidden_attributes_protection = [Foo] # put your filtered classes here

all_models.each do |model|
  unless models_without_forbidden_attributes_protection.include?(model)
    model.send(:include, ActiveModel::ForbiddenAttributesProtection)
  end
end