2

我有以下带有“另存为草稿”功能的代码,该功能应该防止验证运行(即它们应该只在状态不是草稿时运行)。我不确定如何在我的相关模型中了解这一点,以防止它们被验证:

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 ,但这似乎并没有完全达到我想要的效果,因为即使它是空白的,我仍然希望创建记录,以便以后编辑时记录将存在. 如果另存为草稿,我还想允许部分提交。有任何想法吗?

4

2 回答 2

1

不确定这是否足够,但一种可能性是接受当提案为零时,proposal_is_draft?实际上是真的。在这种情况下,您可以将其重新定义为:

def proposal_is_draft?
  !proposal.persisted? || proposal.draft?
end

虽然这看起来不太好,但它会在提案未持久化时返回 true,并在提案为草稿时返回 true(从 status.draft 更改为使用您在 Proposal 类中定义的方法)。

于 2013-08-15T23:11:01.577 回答
0

I never really use accepts_nested_attributes_for, personally, but you might try "rolling your own" validation for the association rather than using the standard model validations, if you're happy to use reject_if on the parent model instead of validating the child model directly.

class Proposal < ActiveRecord::Base

  has_one :primary_presenter, dependent: destroy

  accepts_nested_attributes_for :primary_presenter,
    reject_if: primary_presenter_invalid?

  def primary_presenter_invalid?(attributes)
    return false if draft?
    [:email, :first_name, :last_name, :title].each do |attr|
      return true if attributes[attr].blank?
    end
    false
  end

end

Then I guess remove the validations on the Presenter model. Though it seems like you might still want those, if you ever create or update presenters in any way other than via nested attributes on proposals?

于 2013-08-15T23:32:43.167 回答