Ruby on rails Rails中数据字段_的有条件保存
我有一个rails应用程序,它有一个客户模型和地址模型。客户可以有许多地址。我创建了一个表单,该表单使用字段\以便用户可以在同一表单上输入客户详细信息和地址。 模型在这里 customer.rbRuby on rails Rails中数据字段_的有条件保存,ruby-on-rails,ruby,forms,Ruby On Rails,Ruby,Forms,我有一个rails应用程序,它有一个客户模型和地址模型。客户可以有许多地址。我创建了一个表单,该表单使用字段\以便用户可以在同一表单上输入客户详细信息和地址。 模型在这里 customer.rb class Customer < ApplicationRecord has_many :addresses, dependent: :destroy accepts_nested_attributes_for :addresses end 如果地址的第_1行为空,我希望能够阻止
class Customer < ApplicationRecord
has_many :addresses, dependent: :destroy
accepts_nested_attributes_for :addresses
end
如果地址的第_1行为空,我希望能够阻止保存该地址。我不知道如何测试它是否为空,或者如何防止它作为保存客户的一部分被保存?任何建议都将不胜感激 您可以将验证添加到
地址
模型验证:atype,:line_1,presence:true
然后重写创建
方法,如下所示:
def创建
@客户=客户。新客户参数
如果@customer.save
将_重定向到@customer
其他的
呈现“新”
结束
结束
并添加一段代码以在表单顶部显示错误:
<% if @customer.errors.any? %>
<ul>
<% @customer.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
虽然@Yakov的答案在技术上是正确的,但它会显示一个验证错误,这有时是不需要的
如果要保存客户,即使没有地址,也可以向客户模式添加回调,如下所示:
before_save :mark_addresses_for_removal
def mark_addresses_for_removal
addresses.each do |address|
address.mark_for_destruction unless address.address_line_1?
end
end
如果地址行1文本被清除,这也会导致在编辑客户时删除地址。此外,触发验证的字段将使用类
字段+错误
包装div
元素。您可以添加CSS样式以突出显示有错误的字段。谢谢!这正是我想要的。对我的模型稍加修改-测试是address.line_1?干杯
def new
@customer = Customer.new
@customer.addresses.build
end
def create
@customer = Customer.new customer_params
@customer.save
redirect_to @customer
end
<% if @customer.errors.any? %>
<ul>
<% @customer.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
before_save :mark_addresses_for_removal
def mark_addresses_for_removal
addresses.each do |address|
address.mark_for_destruction unless address.address_line_1?
end
end