Custom Rail Validation for Action

I would like to know if there is a way to use rail checks in a user action.

For example, I would like to do something like this:

validates_presence_of :description, :on => :publish, :message => "can't be blank"

I do basic checks, create and save, but there are so many things that I do not want to demand ahead. That is, they should be able to save a painless record without checking all fields, however, I have a custom “publish” action and a state in my controller and model, which when used should be checked to make sure that the record is 100%

The above example does not work, any ideas?

UPDATE:

My state machine looks like this:

  include ActiveRecord::Transitions
  state_machine do 
    state :draft
    state :active
    state :offline

    event :publish do
      transitions :to => :active, :from => :draft, :on_transition => :do_submit_to_user, :guard => :validates_a_lot?
    end

  end

I found that I could add defenders, but still I would like to use rail checks instead of doing all this using a special method.

+3
2

-, . , , -.

- Model.publish(), - .

- , . - , Model

Class Article < ActiveRecord::Base
  validate :ready_to_publish

  def publish
    self.published = true
    //and anything else you need to do in order to mark an article as published
  end

  private
  def ready_to_publish
    if( published? ) 
      //checks that all fields are set 
      errors.add(:description, "enter a description") if self.description.blank?
    end
  end
end

an_article.publish, article.save . , , , .

+5

"" - "", :

validates_presence_of :description, :if => Proc.new { |a| a.state == 'published' }

,

validates_presence_of :description, :if => Proc.new { |a| a.published? }
+1

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


All Articles