ruby-on-rails - 如果嵌套属性为空,则不会创建 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
表格:
我的问题是我可以创建一个InventoryItem
with a Location
and Bin
name blank ,它创建一个新的Location
and以及and a blankBin
之间的相应关联。我希望当name 或name 在表单中为空时 a new , a new并且不会创建关联。InventoryItem
Location
Location
Bin
Location
Bin
提前致谢
解决方案
您可以像这样添加验证:
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
推荐阅读
- sql - informatica 中的字符串到日期时间
- python-3.x - AWS Lex Lambda 使用 Python 返回多行
- javascript - Quill JS自定义印迹插入文本“true”而不是正确的文本
- google-bigquery - 使用 Logstash BigQuery 插件将数据加载到 BigQuery 时出现异常
- javascript - 无法使用 jQuery AJAX 发送多个数据参数
- python - 将显示凯撒密码字典的 Python 函数
- python - 如何以生产者-消费者模式等待和检索结果?
- php - Android应用程序的Wordpress身份验证
- stored-procedures - 我可以使用 postgres JDBC 驱动程序从 java 调用 postgres“过程”(而不是“函数”)吗?
- java - Java 有(显然)矛盾的作用域