[英]Rails: Check while building/before saving an object if association matching certain condition is there?
[英]Check a condition before saving a nested object in Rails
我这里有3个模型: NewWord
, VerbForm
和AdjForm
。
在NewWord
模型中,我有一列word_type
存储的单词类型: Adj Noun Verb Phrase GenericWord
每个NewWord可以具有1个VerbForm或1个AdjForm
Class NewWord < ApplicationRecord
has_one :adj_form, dependent: :destroy
has_one :verb_form, dependent: :destroy
accepts_nested_attributes_for :adj_form, allow_destroy: true
accepts_nested_attributes_for :verb_form, allow_destroy: true
def self.types
%w(Adj Noun Verb Phrase GenericWord)
end
end
class NewWord::AdjForm < ApplicationRecord
belongs_to :new_word
end
class NewWord::VerbForm < ApplicationRecord
belongs_to :new_word
end
我用这个表格来创建一个单词
<%= simple_form_for new_word, remote: true do |f| %>
<div class="error_section"></div>
<%= f.input :word %>
<%= f.input :kanji_version %>
<%= f.input :word_type, collection: NewWord.types %>
<%= f.simple_fields_for :verb_form do |v| %>
<%= v.input :verb_type %>
<%= v.input :dictionary_form %>
# Other fields
<% end %>
<%= f.simple_fields_for :adj_form do |a| %>
<%= a.input :adj_type %>
# Other fields
<% end %>
<%= f.button :submit %>
<% end %>
我的想法是,当用户从下拉列表中选择word_type
时,我可以使用Javasript隐藏或显示AdjForm
或VerbForm
或两者的字段。 然后在提交时,如果新单词的word_type
为'Adj',则仅保存AdjForm
VerbForm
如果word_type
为'Verb',则仅保存AdjForm
。
那么,我该如何实现呢? 因为当我在新单词create
方法中运行嵌套对象时会自动保存它: @new_word.save.
?
我有尝试reject_if
但它只返回嵌套对象的参数!
accepts_nested_attributes_for :adj_form, allow_destroy: true, reject_if: :not_adj
def not_adj(att)
att['new_word']['word_type'] != 'Adj' # Found out "att" here only has attributes of AdjForm , not NewWord !
end
在控制器中,在保存之前,请检查word_type值并丢弃您不想保存的参数。
new_words_controller.rb
def create
prepare_params
@new_word = NewWord.new(new_word_params)
if @new_word.save
# ...
else
# ...
end
end
private
def prepare_params
params.delete[:verb_form] if params[:word_type] == "Adj"
params.delete[:adj_form] if params[:word_type] == "Verb"
params
end
假设您已将new_word及其关联的参数列入白名单。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.