首页 > 解决方案 > Rails 5.1 多个 belongs_to 关联,可选:true,rollback - '必需的关联'

问题描述

我想belongs_to parent_model, optional: true为 1 个孩子和 2 个父母使用关联。找到了这个答案:Model belongs_to eiher/or more than one models。试过了。但是对于 2 个关联的父模型,其中一个在保存子模型时会导致回滚。

belongs_to对多个父模型有任何限制optional: true吗?还是我错过了其他一些存在验证?重要的是:在这种情况下,我宁愿避免使用多态关联。

PrivateAttachment 有一个使用回形针附加的文件。私人附件.rb

Class PrivateAttachment < ApplicationRecord

  belongs_to :first_class, optional: true
  belongs_to :second_class, optional: true

  has_attached_file :certificate

  validates_attachment_presence :certificate
  validates_attachment_size :certificate, :less_than => 10.megabytes
  validates_attachment_content_type :certificate,
    :content_type => [
      "image/jpg", 
      "image/jpeg", 
      "image/png", 
      "application/pdf",
      "file/txt",
      "text/plain",
      "application/doc",
      "application/msword", 
      "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
      "application/vnd.oasis.opendocument.text",
      ]

end

first_class.rb

Class FirstClass < ApplicationRecord

  validates_length_of :message, :maximum => 2000, allow_blank: true

  has_many :private_attachments, dependent: :destroy
  has_many :approvals
  accepts_nested_attributes_for :approvals

end

second_class.rb

Class SecondClass < ApplicationRecord

  has_many :private_attachments, dependent: :destroy

end

创建 PrivateAttachment 时:

second_class.private_attachments.new(certificate: file)

尽管可选属性设置为 true,但保存时仍有回滚消息。

完全错误

ActiveModel::Errors:0x00007f8bbe03a380 @base=#PrivateAttachment id:nil,first_class_id:nil,company_id:nil,user_id:nil,doc_type:nil,url:nil,活动:nil,blind:nil,permit_period:nil,views:nil ,下载:无,created_at:无,updated_at:无,certificate_file_name:“test.pdf”,certificate_content_type:“application/pdf”,certificate_file_size:443632,certificate_updated_at:“2018-07-24 20:18:20”,second_class_id: 23>, @messages={:first_class=>["要求第一类。"]}, **@details={:first_class=>[{:error=>:blank}]}>

使用 first_class 创建附件时,一切正常,没有错误。

更新 1------------------------------------------------ ---------------------

我刚刚意识到,它有一个有自己验证first_class的子模型。Approval但此时我不明白为什么在使用时要考虑这种深度关联optional: true

approval.rb

class Approval < ApplicationRecord

  belongs_to :job_application

  validates_acceptance_of :operator_approval, :allow_nil => false,

end

导轨 5.1.6。PG数据库

标签: ruby-on-railsruby-on-rails-5.1rails-5.1.6

解决方案


推荐阅读