[英]Rails: How to make nested form only do validation for the outside model?
======代码=====
型号parent.rb&son.rb
class Father < ApplicationRecord
has_many :sons
validates :f_name, presence: true
accepts_nested_attributes_for :sons
end
class Son < ApplicationRecord
belongs_to :father
validates :s_name, presence: true
end
_form.html.erb--父亲
<%= form_for @order do |f| %>
<%= f.text_field :f_name %>
<%= f.fieids_for :sons do |ff| %>
<%= ff.s_name %>
<% end %>
<% end %>
Fathers_controller.rb
def create
@father = Father.new father_params
if @father.save
do_something
end
end
=======问题======
如果我像下面那样保存父亲对象,它将同时验证父亲和儿子。
相反,如果我将其更改为@father.save(validate: false)
,我认为这将跳过两个验证。 我想要的只是对父亲的属性进行验证。 有没有办法做到这一点?
我认为您应该将以下代码添加到模型parent.rb中,以便基本上从验证中拒绝儿子的属性,并且仅会验证父亲的属性:
reject_if: proc { |attributes| attributes['s_name'].blank? }
最终的模型father.rb将是:
class Father < ApplicationRecord
has_many :sons
validates :f_name, presence: true
accepts_nested_attributes_for :sons,
reject_if: proc { |attributes| attributes['s_name'].blank? }
end
UPDATE
( 注意:上面的代码不会将:s_name
属性保存到数据库中,因为@Marco Song在他的问题中没有提到)
对我allow_blank: true
的解决方案是在Son模型中添加allow_blank: true
。 allow_nil: true
在Rails 5.0.0.1和Ruby 2.3.1中对我不起作用
我还向两个模型添加了inverse_of
:以避免SQL查询,而不是生成它们。
父亲模型:
app/models/father.rb
class Father < ApplicationRecord
has_many :sons, inverse_of: :father
validates :f_name, presence: true
accepts_nested_attributes_for :sons
end
子型号:
app/models/son.rb
class Son < ApplicationRecord
belongs_to :father, inverse_of: :sons
validates :s_name, presence: true, allow_blank: true
end
我在父亲的控制器中将儿子的属性列入了白名单:
def father_params
params.require(:father).permit(:f_name, sons_attributes: [:id, :s_name])
end
完成上述设置后,我终于可以在数据库中保存:s_name
属性。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.