Rails 5.0 嵌套改革

Rails 5.0 nested Reform

我有 2 个模型,详细信息如下:

# Device model
module Rubywebit::Devices
  class SensorValue < ApplicationRecord
    belongs_to :device, class_name: Rubywebit::Devices::Device
  end
end

# SensorValue model
module Rubywebit::Devices
  class Device < ApplicationRecord
    has_many :sensor_values, class_name: Rubywebit::Devices::SensorValue
  end
end

我正在使用 Reform gem (https://github.com/apotonick/reform) 创建表单对象。我的 2 模型的表格 类 是以下代码:

# Device form
class DeviceForm < Reform::Form
  property :name
  property :imei
  collection :sensor_values, form: SensorValueForm
end

# SensorValue form
class SensorValueForm < Reform::Form
  property :index
  property :value
  property :date_time
end

如您所见,我有 2 个模型的 2 个嵌套表单。在第 1 步中,一条记录插入 table 并引用:

df=DeviceForm.new(Rubywebit::Devices::Device.new, sensor_values: [Rubywebit::Devices::SensorValue.new]) 
df.validate(name: 'A',imei:'B',sensor_values: [index: 1, value: 2])
df.save

输出为:

(0.6ms)  BEGIN
  SQL (0.5ms)  INSERT INTO "rubywebit_devices_devices" ("name", "imei", "created_at", "updated_at") VALUES (, , , ) RETUR
NING "id"  [["name", "A"], ["imei", "B"], ["created_at", 2016-06-14 05:04:58 UTC], ["updated_at", 2016-06-14 05:04:58 UTC]]
  SQL (0.5ms)  INSERT INTO "rubywebit_devices_sensor_values" ("index", "value", "device_id", "created_at", "updated_at") VALUES (
, , , , ) RETURNING "id"  [["index", 1], ["value", 2.0], ["device_id", 2], ["created_at", 2016-06-14 05:04:58 UTC], ["u
pdated_at", 2016-06-14 05:04:58 UTC]]
   (0.8ms)  COMMIT
   (0.1ms)  BEGIN
   (0.1ms)  COMMIT

这没关系。

在第 2 步中,我们有一条设备记录,我想用我们拥有的 device_id 向 sensor_values table 插入一条记录:

df=DeviceForm.new(Rubywebit::Devices::Device.find(1), sensor_values: [Rubywebit::Devices::SensorValue.new])
df.validate(sensor_values: [index: 2, value: 3])
df.save

输出:

Rubywebit::Devices::SensorValue Load (0.4ms)  SELECT "rubywebit_devices_sensor_values".* FROM "rubywebit_devices_sensor_values"
 WHERE "rubywebit_devices_sensor_values"."device_id" =   [["device_id", 1]]
   (0.2ms)  BEGIN
  SQL (13.1ms)  UPDATE "rubywebit_devices_sensor_values" SET "device_id" = NULL WHERE "rubywebit_devices_sensor_values"."device_i
d" =  AND "rubywebit_devices_sensor_values"."id" = 17  [["device_id", 1]]
  SQL (0.5ms)  INSERT INTO "rubywebit_devices_sensor_values" ("index", "value", "device_id", "created_at", "updated_at") VALUES (
, , , , ) RETURNING "id"  [["index", 1], ["value", 2.0], ["device_id", 1], ["created_at", 2016-06-14 05:19:51 UTC], ["u
pdated_at", 2016-06-14 05:19:51 UTC]]
   (0.6ms)  COMMIT
   (0.1ms)  BEGIN
   (0.1ms)  COMMIT
   (0.1ms)  BEGIN
   (0.1ms)  COMMIT

如您所见,Reform 进行了额外的交易 (UPDATE "rubywebit_devices_sensor_values" ...) 为什么?

我通过 Populate_if_empty 功能解决了这个问题。

https://github.com/trailblazer/reform/issues/370