Ruby on rails 验证名称,但不验证该名称是否存在于集合\u复选框中

Ruby on rails 验证名称,但不验证该名称是否存在于集合\u复选框中,ruby-on-rails,Ruby On Rails,我的项目允许用户创建超级英雄,并使用嵌套属性将其与团队关联。问题是,如果以前创建了团队并在集合\u复选框中选中了该复选框,“创建新团队”文本\u字段仍要求用户键入并输入新团队。换句话说,我不断得到一个错误,text\u字段不能留空,无论用户是否选中集合中的一个或多个复选框 如果团队:name已存在于集合复选框中,我希望验证:name的存在。如果复选框中不存在,则在:nametext\u字段中运行验证 我尝试了很多步骤,但仍然无法理解。我最好的假设是,我需要创建一个自定义方法来实现这一点。以下是我

我的项目允许用户创建超级英雄,并使用嵌套属性将其与团队关联。问题是,如果以前创建了团队并在
集合\u复选框中选中了该复选框
,“创建新团队”
文本\u字段
仍要求用户键入并输入新团队。换句话说,我不断得到一个错误,
text\u字段
不能留空,无论用户是否选中
集合中的一个或多个复选框

如果团队
:name
已存在于
集合复选框中,我希望
验证:name
的存在。如果复选框中不存在,则在
:name
text\u字段中运行验证

我尝试了很多步骤,但仍然无法理解。我最好的假设是,我需要创建一个自定义方法来实现这一点。以下是我的项目截图:

超级英雄

class Superhero < ApplicationRecord
    belongs_to :user
    has_many :superhero_teams
    has_many :teams, through: :superhero_teams

    validates_presence_of :name

    accepts_nested_attributes_for :teams, reject_if: proc { |attributes| attributes['name'].blank?}

    def teams_attributes=(team_attributes)
        team_attributes.values.each do |team_attribute|
          team = Team.find_or_create_by(team_attribute)
          self.teams << team
        end
    end
end
class超级英雄class Team < ApplicationRecord
    has_many :superhero_teams
    has_many :superheroes, through: :superhero_teams

    validates_presence_of :name
end
<h1>CREATE A SUPERHERO</h1>

<%= form_for(@superhero) do |f| %>

    <%= render partial: "layouts/error", locals: {object: @superhero} %>

    <div class="field">
      Superhero Name
      <%= f.text_field :name %>
      <br>
      <br>
    </div>
  
    <div class="field">
    <% if Team.exists? %>
        Select Team:
        <%= f.collection_check_boxes :team_ids, Team.all, :id, :name %>
        <br><br>
    <% end %>
    </div>
  
    <div class="field">
     Create a new Team:
      <%= f.fields_for :teams, @superhero.teams.build do |teams_fields| %>
        <%= teams_fields.text_field :name %>
      <% end %>
    </div>
    
    <div class="actions">
    <br>
      <%= f.submit %>
    </div>
  
<% end %>