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