Validate ActiveRecord by Parent Attribute

I have a model article, for example. Article has_one ArticleContent. ArticleContent by default checks all attributes. But I need additional functionality - to save the draft article without any verification. So I pass: draft => false as one of the parameters in the .new () article, then I do @ article.build_article_content (). ArticleContent has invalid code:

  def draft?
    raise self.article.draft
  end

  validates_presence_of :header, :message => "We have no fuckin' header!", :unless => :draft?

Of course, this will not work. At the time of the project? execution there is no suitable article object anywhere, therefore self.article returns nil. Nice try, codemonkey ...

Anyone have any sweet ideas? I think to do @ content.save! not a good idea

UPDATE

I tried like this:

def draft
    self[:draft]
end

def draft=(value)
    self[:draft] = value
end

def draft?
    self[:draft]
end

validates_presence_of :field1, :message => "msg1", :unless => :draft?
validates_presence_of :field2, :message => "msg2", :unless => :draft?
validates_presence_of :field3, :message => "msg3", :unless => :draft?

This works, but how can I group this?

unless self.draft?
    validates_presence_of :field1, :message => "msg1"
    validates_presence_of :field2, :message => "msg2"
    validates_presence_of :field3, :message => "msg3"
end

, ? .

@article.content.draft = @article.draft

- .

+3
1

. rails.

http://ruby-toolbox.com/categories/state_machines.html

, - ArticleContent. "", "", "" .. , , :

validates :content, :presence => true, :unless => Proc.new { |a| a.state == "Draft" }

( , , , .)

UPDATE

with_options.

with_options :unless => :draft? do |o|
    o.validates_presence_of :field1, :message => "msg1"
    o.validates_presence_of :field2, :message => "msg2"
    o.validates_presence_of :field3, :message => "msg3"
end

, . , errors.add(blah), . , , , . , AR .

+2

Source: https://habr.com/ru/post/1785153/


All Articles