使has_many / belongs_to关联不可变

时间:2009-07-27 09:36:19

标签: ruby-on-rails activerecord

假设我的发票类有很多与之相关的项目。如何确保在保存发票后,不能在发票中添加或删除任何项目?

我已经使用immutable attributes plugin来处理常规字段,但它不处理关联。使用attr_readonly也不起作用。

1 个答案:

答案 0 :(得分:1)

has_many有一个:readonly选项,它使集合中的所有项都不可变(api-link)。然而,遗憾的是,这似乎并不妨碍创建新项目。

class Invoice
  has_many :items, :readonly => true
end

要真正使集合在Invoice类中不可变,您可以重新定义现有记录的items访问者和#freeze集合:

class Invoice
  def items_with_immutability
    items = items_without_immutability
    items.freeze unless new_record?
    items
  end
  alias_method_chain :items, :immutability
end