通过has_many的Rails验证消息

时间:2019-06-03 08:39:37

标签: ruby-on-rails validation activerecord

保存时,我无法访问相关模型的验证消息。设置是“记录”可以通过“ RecordRelation”链接到许多其他记录,“ RecordRelation”具有说明该关系是什么的标签,例如记录“ refers_to”或“替换”另一个记录:

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的验证吗?这将对用户有用。

1 个答案:

答案 0 :(得分:1)

以您的示例为例,我更愿意使用nested_attributes。然后,您应该可以轻松访问相关的记录错误。使用它的另一个好处是可以删除针对这种行为编写的自定义逻辑。

有关更多信息,请查看文档-https://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html