我正在创建一个嵌套表单,其中包含来自不同模型的属性。在保存新对象之前,我希望所有必需的属性都有效。
<%= form for @product do |f| %>
<%= f.fields_for @customer do |g| %>
<%= g.label :name %>
<%= g.text_field :name %>
<%= g.label :email %>
<%= g.text_field :email %>
<%= g.label :city %>
<%= g.text_field :city %>
<%= g.label :state %>
<%= g.text_field :state %>
<%= g.label :zipcode %>
<%= g.text_field :zipcode %>
<% end %>
<%= f.label :product %>
<%= f.text_field :product %>
<%= f.label :quantity %>
<%= number_field(:quantity, in 1..10) %>
<% end %>
这是我的模型
class Product < ActiveRecord::Base
belongs_to :customer
validates_associated :customer
validates :product, :presence => "true"
end
class Customer < ActiveRecord::Base
has_one :product
validates :name, :email, presence: true
validates :email, format: { with: /[A-Za-z\d+][@][A-Za-z\d+][.][A-Za-z]{2,20}\z/ }
validates :city, presence: true
validates :zipcode, format: { with: /\A\d{5}\z/ }
end
我将 validates_associated
添加到我的产品模型中,因此我的 form_for @product
应该要求所有客户验证通过。这意味着姓名、电子邮件、城市和邮政编码必须存在并且必须正确格式化。
我摆弄了一下,没有填写客户必填字段就提交了表格,表格被认为是有效的。
我不明白我的错误在哪里。
编辑
好的,所以通过添加 validates :customer
,现在需要客户属性。但它们实际上并没有保存到数据库中。我认为这与我的参数有关
def product_params
params.require(:product).permit(:product, :quantity)
end
我是否需要将我的客户参数添加到我的允许参数列表中?
最佳答案
validates_associated
方法仅在对象存在时验证关联对象,因此如果您将表单字段留空,您正在创建/编辑的 Product
将验证,因为没有关联的 Customer
.
相反,假设您使用的是 Rails 4+,您想使用 accepts_nested_attributes_for :customer
,以及 validates :customer, presence: true
以便在您的产品表单中要求客户字段。
如果您使用的是 Rails 3,则 accepts_nested_attributes_for
将不适用于 belongs_to
关联。相反,您的 Customer
类将需要使用 accepts_nested_attributes_for :product
,并且您需要相应地更改表单 View 。
更新
您还需要允许您的 Controller 操作接受:customer
关联的参数:
def product_params
params.require(:product).permit(:product, :quantity, :customer_attributes => [:name, :email, :city, :state, :zipcode])
end
值得注意的是,由于您的客户表单字段中没有:id
字段,并且您的产品表单字段中没有:customer_id
字段,因此您将创建一个新的客户每次成功提交产品表单。
关于ruby-on-rails - Rails - 如何使用嵌套属性验证表单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27263172/