首页 > 解决方案 > 如果嵌套属性为空,则不会创建 Rails 嵌套属性

问题描述

我在以下之间有一个嵌套属性:

class InventoryItem < ApplicationRecord
  belongs_to :location
  accepts_nested_attributes_for :location
end

class Location < ApplicationRecord
  has_many :inventory_items
  has_many :bins
  accepts_nested_attributes_for :bins
end

class Bin < ApplicationRecord
  belongs_to :location
end

inventory_item表格:

  <%= form.fields_for :location do |location| %>
    <div class="field">
      <%= location.label :location_name %>
      <%= location.text_field :name %>
    </div>
      <%= location.fields_for :bins do |bin| %>
        <div class="field">
          <%= bin.label :bin_name %>
          <%= bin.text_field :name %>
      </div>
      <% end %>
    </div>
  <% end %>

inventory_item控制器中:

  def new
    @inventory_item = InventoryItem.new
    @inventory_item.build_location.bins.build
  end

  def inventory_item_params
    params.require(:inventory_item).permit(:location_id, location_attributes:[:name, bins_attributes:[:name]])
  end

表格:

在此处输入图像描述

我的问题是我可以创建一个InventoryItemwith a Locationand Binname blank ,它创建一个新的Locationand以及and a blankBin之间的相应关联。我希望当name 或name 在表单中为空时 a new , a new并且不会创建关联。InventoryItemLocationLocationBinLocationBin

提前致谢

标签: ruby-on-railsruby

解决方案


您可以像这样添加验证:

accepts_nested_attributes_for :location, reject_if: proc { |l| l[:name].blank? }

或者您也可以在InventoryItem模型中创建一个方法来拒绝和调用,如下所示:

accepts_nested_attributes_for :location, reject_if: :reject_method?

def reject_method(attributes)
  attributes['name'].blank?
end

在此处阅读有关语法的更多信息:https ://api.rubyonrails.org/classes/ActiveRecord/NestedAttributes/ClassMethods.html


推荐阅读