ここに3モデルあります:NewWord
、VerbForm
およびAdjForm
です。 NewWord
モデルで入れ子オブジェクトをRailsに保存する前に条件を確認してください
、Iは単語の列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
を選択したとき、私はJavasripを使用することができますですフィールドを非表示にするかAdjForm
またはVerbForm
、またはその両方のフィールドを表示します。その後、提出時に、新しい単語のword_type
が「Adj」の場合はAdjForm
、word_type
の場合はVerbForm
が「Verb」の場合のみ保存されます。
これをどのように達成できますか?ネストされたオブジェクトは、新しい単語create
のメソッドでこれを実行すると自動的に保存されるので、@new_word.save.
?
私は試してみましたが、reject_if
を入れましたが、ネストされたオブジェクトだけのためにparamsを返します!
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