【问题标题】:Rails 3.1 validates uniqueness of nested attributes for polymorphic associationRails 3.1 为多态关联验证嵌套属性的唯一性
【发布时间】:2011-11-11 19:12:25
【问题描述】:

鉴于以下模型:

##Invoice.rb
has_many :line_items, :as => :line_itemable
accepts_nested_attributes_for :line_items

##LineItem.rb
belongs_to :line_itemable, :polymorphic => true
validates :employee_id, :presence => true, :uniqueness => { :scope => [ :line_itemable_id, :line_itemable_type ] }

我将如何验证以下新发票

i = Invoice.new
i.line_items << [ LineItem.new( :employee_id => 1 ), LineItem.new( :employee_id => 1 ) ]
i.valid?

发票应该是无效的,因为 line_items 的employee_id 是相同的,但没有抛出错误,并且 line_items 已添加到数据库中。如果发票是现有记录,则验证确实有效。

有什么想法吗?这是一个错误吗?

为了防止错误数据,我添加了以下索引,但希望有适当的 rails 验证

add_index :line_items, [ :employee_id, :line_itemable_type, :line_itemable_id ], :unique => true, :name => 'index_line_item_employee_id'

【问题讨论】:

  • 有没有想过这个问题?我刚刚遇到了同样的问题。似乎是因为 line_itemable_id 尚未填写并且为零,因此验证不会失败。

标签: ruby-on-rails-3 polymorphic-associations nested-attributes


【解决方案1】:

我想完全按照您的方式编写代码,但我发现绕过它的唯一方法是在 Invoice 类中编写自定义验证。此解决方案的缺点是无法突出显示有问题的字段。

【讨论】:

    猜你喜欢
    • 2014-09-20
    • 1970-01-01
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 2022-11-15
    • 1970-01-01
    • 1970-01-01
    • 2018-10-23
    相关资源
    最近更新 更多