[英]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.