【问题标题】:Rails: list all attributes that can't be mass assignedRails:列出所有不能批量分配的属性
【发布时间】:2014-10-22 12:04:56
【问题描述】:

我正在处理一个最近更新的旧项目。该项目的模型在独立于控制器和视图等运行的引擎中运行。引擎在 Rails 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 个。

有没有办法突出显示、查找、测试、发现这个错误还可能出现在哪些其他模型中?

【问题讨论】:

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


    【解决方案1】:

    我认为您正在寻找的可能是这样的:

    Object.attributes.keys - Object.accessible_attributes
    

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

    【讨论】:

      【解决方案2】:

      感谢@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 的关系并动态生成它。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-25
        • 1970-01-01
        • 2011-03-29
        • 1970-01-01
        • 2012-01-26
        • 1970-01-01
        • 2013-06-03
        相关资源
        最近更新 更多