首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >正在验证表单中至少存在一个字段

正在验证表单中至少存在一个字段
EN

Stack Overflow用户
提问于 2021-05-25 10:12:21
回答 2查看 43关注 0票数 0

我在这方面已经坚持了一段时间,不知道如何为superpower验证至少一个字段。换句话说,如果至少填充了一个字段,则可以将其他字段留空。我确实为superpowers使用了reject_if: proc { |attributes| attributes['name'].blank?},但这样做将允许在所有三个超级域都留空时提交表单,而这不是我想要的。

Here is a screenshot of my project

superpower.rb

代码语言:javascript
复制
class Superpower < ApplicationRecord
    belongs_to :superhero
    
    validates_presence_of :name
end

superhero.rb

代码语言:javascript
复制
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
EN

回答 2

Stack Overflow用户

发布于 2021-05-25 12:39:59

为了方便起见,您可以传递符号:all_blank,这将创建一个进程,该进程将拒绝所有属性为空的记录,但不包括_destroy的任何值

accepts_nested_attributes_for :superpowers, reject_if: :all_blank

票数 0
EN

Stack Overflow用户

发布于 2021-05-25 14:45:39

也许只需要添加一个新的验证

代码语言:javascript
复制
  validates_presence_of :superpowers

因此,如果名称为空,您将拒绝超级大国,并且这个新的验证将确保至少有一个超级大国具有该名称。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/67680872

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档