【问题标题】:Reordering Uniquely Ordered Models in ActiveRecord Association在 ActiveRecord 关联中重新排序唯一排序的模型
【发布时间】:2013-04-24 22:45:29
【问题描述】:

我有很多项目的列表模型。这些项目有一个priority,在列表范围内是唯一的。

class List < ActiveRecord::Base
  has_many :items
  accepts_nested_attributes_for :items
end

class Item < ActiveRecord::Base
  validates :priority, uniqueness: { :scope => :list_id }
end

因此,如果我从 API 调用返回给定列表,它看起来像这样:

{
  items: [
    { "id": 1, "priority": 1 },
    { "id": 2, "priority": 2 },
    { "id": 3, "priority": 3 }
  ]
}

用户在前端重新排列项目并向服务器发出PUT请求

{
  items_attributes: [
    { "id": 1, "priority": 3 },
    { "id": 2, "priority": 1 },
    { "id": 3, "priority": 2 }
  ]
}

但这会失败。当其中一个尝试保存时,它将检查是否存在具有相同列表 ID 和优先级的另一个项目。由于数据库中的其他项目尚未更新,因此此验证将失败。

如何实现此更新?

【问题讨论】:

    标签: validation activerecord model-associations


    【解决方案1】:

    允许在 list_id 列中使用 nil,以便您可以重置值。

    validates :priority, uniqueness: { :scope => :list_id }, unless: Proc.new { |l| l.list_id.blank? }
    

    在您的控制器中,重置列:

    ItemController.update_all("priority = null");
    

    然后像现在一样使用传递的参数设置它们。只需确保在保存之前测试模型的有效性 (valid?)。

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-05
      • 2023-03-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多