【问题标题】:Rails nested attributes with no creation if nested attributes are blank如果嵌套属性为空,则不会创建 Rails 嵌套属性
【发布时间】:2021-07-16 11:46:58
【问题描述】:

我有一个嵌套属性:

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

形式:

我的问题是我可以创建一个LocationBin 名称为空白的InventoryItem,它会创建一个新的LocationBin 以及InventoryItem 和空白@987654334 之间的相应关联@。 我希望当Location 名称或Bin 名称在表单中为空白时,新的Location、新的Bin创建关联。

提前致谢

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

    您可以像这样添加验证:

    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

    【讨论】:

    • 谢谢@deepesh,我现在的问题是Location must exist
    • 您可以添加validates_presence_of :location 以检查InventoryItem 模型
    • 抱歉@deepesh 这个验证我现在选择了两个错误。 Location must existLocation can't be blank 如果为空白,我想创建没有 LocationInventoryItem
    • Location can't be blank 来自我们上面添加的验证,must exist 来自belongs_to 关联。
    猜你喜欢
    • 1970-01-01
    • 2011-02-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多