我有一个问题。
我有一个内容模型,它具有多态关联,赞助。
在我的内容表单中,我有一个带有一些赞助细节的嵌套表单。这些赞助详细信息不是强制性的,但现在每次编辑内容时,赞助表都会填充空白数据。
我将在这里简化我的代码:
class Content < ActiveRecord::Base
include Sponsorable
end
class Sponsorship < ActiveRecord::Base
belongs_to :sponsorable, polymorphic: true
end
module Sponsorable
extend ActiveSupport::Concern
included do
has_one :sponsorship, as: :sponsorable
accepts_nested_attributes_for :sponsorship
end
end
我需要澄清一下,我在内容模型上创建了一个自动保存功能,所以在我的内容控制器中,我将Content.create放在“new”方法中。
def new
@content = Content.create(author: current_user)
redirect_to edit_admin_content_path(@content)
end
并填写赞助细节
def edit
content.build_sponsorship unless content.sponsorship
end
每次创建和保存内容时,如果我将表单字段留空,也会创建赞助详细信息。我的内容表有一个布尔“赞助商”:有没有办法只在sponsor == true
时保存关联?
答案 0 :(得分:0)
您可能需要查看accepts_nested_attributes_for
的reject_if:
选项:
accepts_nested_attributes_for :sponsorship, reject_if: proc { |attributes| attributes['title'].blank? }
在这件事上查看other questions似乎证实了这一点。
-
accepts_nested_attributes_for :sponsorship, reject_if: :all_blank