我有以下带有“另存为草稿”功能的代码,该功能应该防止验证运行(即它们应该只在状态不是草稿时运行)。我不确定如何在我的相关模型中了解这一点,以防止它们被验证:
class Proposal < ActiveRecord::Base
belongs_to :user
has_one :primary_presenter, dependent: :destroy
validates :title, presence: true
validates :primary_presenter, presence: true, unless: :draft?
validates :abstract, presence: true, unless: :draft?
validates :description, presence: true, unless: :draft?
accepts_nested_attributes_for :primary_presenter
def draft?
status.draft?
end
end
class Presenter < ActiveRecord::Base
belongs_to :proposal
validates :email, presence: true, unless: :proposal_is_draft?
validates :first_name, presence: true, unless: :proposal_is_draft?
validates :last_name, presence: true, unless: :proposal_is_draft?
validates :title, presence: true, unless: :proposal_is_draft?
def proposal_is_draft?
proposal.status.draft?
end
end
class PrimaryPresenter < Presenter
end
当然,问题是presenter.proposal 在记录尚未保存时为nil。我已经查看了嵌套属性的 reject_if: :all_blank ,但这似乎并没有完全达到我想要的效果,因为即使它是空白的,我仍然希望创建记录,以便以后编辑时记录将存在. 如果另存为草稿,我还想允许部分提交。有任何想法吗?