【发布时间】:2019-06-03 08:39:37
【问题描述】:
我在保存时无法访问相关模型的验证消息。设置是“记录”可以通过“记录关系”链接到许多其他记录,“记录关系”有一个标签,说明该关系是什么,例如一条记录“引用”或“替换”另一条记录:
class Record < ApplicationRecord
has_many :record_associations
has_many :linked_records, through: :record_associations
has_many :references, foreign_key: :linked_record_id, class_name: 'Record'
has_many :linking_records, through: :references, source: :record
...
end
class RecordAssociation < ApplicationRecord
belongs_to :record
belongs_to :linked_record, :class_name => 'Record'
validates :label, presence: true
...
end
在控制器中创建记录如下所示:
def create
# Record associations must be added separately due to the through model, and so are extracted first for separate
# processing once the record has been created.
associations = record_params.extract! :record_associations
@record = Record.new(record_params.except :record_associations)
@record.add_associations(associations)
if @record.save
render json: @record, status: :created
else
render json: @record.errors, status: :unprocessable_entity
end
end
在模型中:
def add_associations(associations)
return if associations.empty? or associations.nil?
associations[:record_associations].each do |assoc|
new_association = RecordAssociation.new(
record: self,
linked_record: Record.find(assoc[:linked_record_id]),
label: assoc[:label],
)
record_associations << new_association
end
end
唯一的问题是如果创建的关联不正确。而不是看到实际原因,我得到的错误是对记录的验证,即
{"record_associations":["is invalid"]}
任何人都可以提出一种方法来让我恢复 record_association 的验证吗?这对用户来说是有用的信息。
【问题讨论】:
-
您能否在此处添加包含此表单的视图文件?
-
不,因为没有。这是一个 API 应用程序,因此只有 JSON 来回传递。
标签: ruby-on-rails validation activerecord