【问题标题】:Rails validation messages for has_many throughhas_many 的 Rails 验证消息
【发布时间】: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


【解决方案1】:

对于你的例子,我宁愿选择nested_attributes。然后,您应该可以轻松访问相关的记录错误。使用它的另一个好处是删除您为此类行为编写的自定义逻辑。

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

【讨论】:

  • 谢谢,我去看看。
  • 确实,通过将数据作为 record_associations_attributes 传递,我能够删除我的自定义逻辑并且所有测试仍然通过,所以这似乎很好地解决了问题 - 谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-10-21
相关资源
最近更新 更多