我想对1个孩子和2个父母使用belongs_to parent_model, optional: true
关联。找到了这个答案:Model belongs_to eiher/or more than one models。试过了。但是对于2个关联的父模型,其中之一会在保存子模型时导致回滚。
具有多个父模型和belongs_to
的{{1}}是否有限制?还是我缺少其他一些在线状态验证?
重要提示:在这种情况下,我宁愿避免使用多态关联。
PrivateAttachment具有使用回形针附加的文件。 private_attachment.rb
optional: true
first_class.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
second_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
创建PrivateAttachment时:
Class SecondClass < ApplicationRecord
has_many :private_attachments, dependent: :destroy
end
尽管可选属性设置为true,但保存消息时会回滚。
完全错误
ActiveModel :: Errors:0x00007f8bbe03a380 @ base =#PrivateAttachment ID: nil,first_class_id:nil,company_id:nil,user_id:nil,doc_type: 零,网址:无,活动:无,盲人:无,permit_period:无,观看次数: 无,下载次数:无,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 =>:空白}]}>
使用first_class创建附件时,一切正常,没有错误。
更新1 --------------------------------------------- ------------------------
我刚刚意识到,second_class.private_attachments.new(certificate: file)
有一个子模型first_class
,它具有自己的验证。但是目前我不明白为什么在使用Approval
时应该考虑这种深层关联?
optional: true
Rails 5.1.6。 PG数据库