我在这方面已经坚持了一段时间,不知道如何为superpower验证至少一个字段。换句话说,如果至少填充了一个字段,则可以将其他字段留空。我确实为superpowers使用了reject_if: proc { |attributes| attributes['name'].blank?},但这样做将允许在所有三个超级域都留空时提交表单,而这不是我想要的。
Here is a screenshot of my project
superpower.rb
class Superpower < ApplicationRecord
belongs_to :superhero
validates_presence_of :name
endsuperhero.rb
class Superhero < ApplicationRecord
belongs_to :user
has_many :superhero_teams
has_many :teams, through: :superhero_teams
has_many :superpowers
validates_presence_of :name
validates_uniqueness_of :name
accepts_nested_attributes_for :teams, reject_if: proc { |attributes| attributes['name'].blank?}
accepts_nested_attributes_for :superpowers, reject_if: proc { |attributes| attributes['name'].blank?}
end发布于 2021-05-25 12:39:59
为了方便起见,您可以传递符号:all_blank,这将创建一个进程,该进程将拒绝所有属性为空的记录,但不包括_destroy的任何值
accepts_nested_attributes_for :superpowers, reject_if: :all_blank
发布于 2021-05-25 14:45:39
也许只需要添加一个新的验证
validates_presence_of :superpowers因此,如果名称为空,您将拒绝超级大国,并且这个新的验证将确保至少有一个超级大国具有该名称。
https://stackoverflow.com/questions/67680872
复制相似问题