代码之家  ›  专栏  ›  技术社区  ›  daveomcd

当我尝试在Rails 5中添加占位符关联记录时,嵌套字段窗体出错。

  •  0
  • daveomcd  · 技术社区  · 7 年前

    我有两个Rails型号: workout , measurable . 当我转到表单编辑训练时,出现以下错误。

    访问训练时出错编辑

    *** ActiveRecord::NotNullViolation Exception: TinyTds::Error: Cannot insert the value NULL into column 'value', table 'bane-development.dbo.measurables'; column does not allow nulls. INSERT fails.: EXEC sp_executesql N'INSERT INTO [measurables] ([measurable_type_id], [workout_id], [created_at], [updated_at], [import_key]) OUTPUT INSERTED.[id] VALUES (@0, @1, @2, @3, @4)', N'@0 int, @1 int, @2 datetime, @3 datetime, @4 int', @0 = 3, @1 = 689349, @2 = '05-29-2018 09:22:45.206', @3 = '05-29-2018 09:22:45.206', @4 = -1
    

    我要做的是填充我的轨道 训练 表单可供用户选择填写要添加到训练中的各种测量值。但是,如果它们没有值,我不希望它们保存到数据库中。但当以下行执行时 self.measurables << Measurable.new(measurable_type_id: measurable_type.id, order_by: 1, import_key: -1) -当我还不想保存到数据库时,它似乎正在尝试保存到数据库中…我只想让它给用户字段输入数据,如果他们选择的话。如何才能让它将关联添加到表单,但在更新 训练 对象?

    训练.rb

    class Workout < ApplicationRecord
      before_validation :remove_blank_measurables
    
      has_many :measurables, inverse_of: :workout
      accepts_nested_attributes_for :measurables, :allow_destroy => true, reject_if: proc {|m| m[:value].blank?}
    
      def add_missing_measurable_types
        MeasurableType.workout_observations.each do |measurable_type|
          if !self.has_measurable_type?(measurable_type)
            self.measurables << Measurable.new(measurable_type_id: measurable_type.id, order_by: 1, import_key: -1)
          end
        end
      end
    
    end
    

    可测量.rb

    class Measurable < ApplicationRecord
      belongs_to :workout
    end
    

    训练编辑

    def edit
      @workout.add_missing_measurable_types
    end
    
    1 回复  |  直到 7 年前
        1
  •  1
  •   D1ceWard    7 年前

    来自 documentation

    集合<<(对象,) 通过在联接表中创建关联,将一个或多个对象添加到集合中(collection.push和collection.concat是此方法的别名)。 请注意,此操作立即激发更新SQL,而不等待对父对象的save或update调用。

    “<<'(电铲操作员)触发更新/保存,您应该使用

    self.measurables.new(measurable_type_id: measurable_type.id, order_by: 1, import_key: -1)