我有2个模型:文档和关键字。它们相互之间是相互关联的。
在我的新文件表格中,我这样做:
<%= form_for @document, url: admin_add_doc_path, :html => {:multipart => true } do |f| %>
<%= f.fields_for @keywords do |words| %>
在模型中我有这个:
class Document < ApplicationRecord
validates_associated :keywords
和
class Keyword < ApplicationRecord
validates :keyword, presence: true
在document_controller中,我有:
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 :(得分:0)
尝试初始化Keyword
这样的对象,
@keywords = @document.keywords.new
此外,在Document
模型中,添加此
has_many :keywords
validates :keywords, presence: true
希望有所帮助!