2017-01-31 3 views
0

私は2つのモデルを持っています:文書とキーワード。彼らはお互いに関係している。habtmの関係でfields_forをどのように検証すればよいですか?

class Document < ApplicationRecord 
validates_associated :keywords 

と::

class Keyword < ApplicationRecord 
validates :keyword, presence: true 

そして、私が持っているdocument_controllerで私はこれを持っているモデルでは

<%= form_for @document, url: admin_add_doc_path, :html => {:multipart => true } do |f| %> 
<%= f.fields_for @keywords do |words| %> 

:私の新しい文書形式で

、私はこれを行います:

def create 
    @document = Document.new(document_params) 
    @keywords = Keyword.new 

    if @document.save 
    @last_doc = Document.last 
    a.each { |var| @document.keywords << Keyword.find(var) } #a = each keyword 
    redirect_to see_doc_url(@last_doc) 
    else 
    render 'new' 
    end 
end 

このコードは、キーワードが存在しない場合でもフォームを検証します。検証を実行してキーワードを入力しないとフォームに戻す方法はありますか?

答えて

0
てみてください、このような Keywordオブジェクトを初期化

@keywords = @document.keywords.new 

また、Documentモデルでは、役立ちます。この

has_many :keywords 
validates :keywords, presence: true 

希望を追加!

関連する問題