2016-09-02 1 views
0

ここに3モデルあります:NewWordVerbFormおよび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」の場合はAdjFormword_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 

答えて

0

保存する前に、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のパラメータとその関連付けをホワイトリストに登録している前提としています。

関連する問題