1

我有 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

我正在使用改革 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 中,一条记录插入到带有引用的表中:

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 ($1, $2, $3, $4) 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 (
$1, $2, $3, $4, $5) 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 表中:

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" = $1  [["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" = $1 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 (
$1, $2, $3, $4, $5) 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" ...) 为什么?

4

1 回答 1

1

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

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

于 2016-12-27T05:43:10.757 回答