2017-01-31 2 views
0

Ich habe 2 Modelle: Dokument und Schlüsselwort. Sie sind im Verhältnis zueinander.Wie validiere ich fields_for in isttm relation?

In meiner neuen Dokument Form, ich dies tun:

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

Im Modell habe ich dies:

class Document < ApplicationRecord 
validates_associated :keywords 

und:

class Keyword < ApplicationRecord 
validates :keyword, presence: true 

Und in den document_controller Ich habe :

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 

Dieser Code validiert das Formular, auch wenn keine Schlüsselwörter vorhanden sind. Wie sollte ich diese Validierung durchführen und sie zurück an Formular senden, wenn keine Schlüsselwörter eingegeben werden?

Antwort

0

Try Keyword Objekt wie dieses,

@keywords = @document.keywords.new 

Auch in Document Modell, fügen Sie diese

has_many :keywords 
validates :keywords, presence: true 

Hoffnung initialisiert, das hilft!