![](/img/trans.png)
[英]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.