簡體   English   中英

在Rails中保存嵌套對象之前檢查條件

[英]Check a condition before saving a nested object in Rails

我這里有3個模型: NewWordVerbFormAdjForm

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隱藏或顯示AdjFormVerbForm或兩者的字段。 然后在提交時,如果新單詞的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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM