Rails:列出无法批量分配的所有属性

时间:2014-10-22 12:04:56

标签: ruby-on-rails ruby ruby-on-rails-3 rspec

我正在处理最近更新的旧遗留项目。该项目的模型位于一个独立于控制器和视图等的引擎中。引擎在轨道4.1.6上运行,而控制器等在Rails 3上运行。

这导致了批量分配的许多问题。我创建了一个读取db列的小模块,白色列出了该模型的属性。但是,在诸如此NewsItem模型的情况下,该模型具有关联并且需要接受这些关联的属性,该模块不起作用。

class Newsitem < ActiveRecord::Base

  include MyAttrAccessibleModule

  has_and_belongs_to_many :assets
  has_and_belongs_to_many :boroughs
  has_and_belongs_to_many :venues

我需要添加

  attr_accessible :asset1_attachment_remove, 
                  :asset1_attachment_title, 
                  :asset2_attachment_title, 
                  :asset3_attachment_title, 
                  :asset4_attachment_title, 
                  :borough_ids, 
                  :venue_ids

但是找到所有需要这个的模型有点痛苦,因为有超过100个。

有没有办法突出显示,查找,测试,发现其他模型中可能出现此错误?

2 个答案:

答案 0 :(得分:2)

我认为您正在寻找的是:

Object.attributes.keys - Object.accessible_attributes

这应该从所有可用的属性中减去所有列入白名单的属性。

答案 1 :(得分:0)

感谢@Stefan Dorunga的建议。它使我朝着正确的方向前进。

if reflect_on_all_associations(:has_and_belongs_to_many).any?
  association = reflect_on_all_associations(:has_and_belongs_to_many)
  association.each {|model| attr_accessible model.plural_name.singularize + "_id"}
  association.each {|model| attr_accessible model.plural_name}
end

我查询模型以查看它是否有关系id未明确列出的关系,并动态生成它。

唯一的缺点是我必须在所有列出的关联之后包含该模块。我通常在课程顶部包含模块。这是否是标准做法我不知道。

相关问题