Validate model for specific actions

I need to check the model only for a specific action (: create). I know this is not a very good tactic, but I just need to do this in my case.

I tried using something like:

validate :check_gold, :if => :create

or

validate :check_gold, :on => :create

But I get errors. The problem is that I can’t check the user checks check_gold when editing, but only to create (since the gold check should only be done when creating the alliance, not editing).

Thanx for reading :)


I am adding some actual code:

  attr_accessor :required_gold, :has_alliance
  validate :check_gold
  validate :check_has_alliance

This is the Alliance model .: required_gold and: has_alliance are set in the controller (they are virtual attributes because I need information from the controller). Valid validators are now:

  def check_gold
    self.errors.add(:you_need, "100 gold to create your alliance!") if required_gold < GOLD_NEEDED_TO_CREATE_ALLIANCE
  end

  def check_has_alliance
    self.errors.add(:you_already, "have an alliance and you cannot create another one !") if has_alliance == true
  end

, , .

+3
3

ActiveRecord :on.

validates_numericality_of :value, :on => :create 

validate_on_create validate:

validate_on_create :check_gold
validate_on_create :check_has_alliance

Edit:

validates_each, , .

validates_each :required_gold, :has_alliance, :on => :create do |r, attr, value|
  r.check_gold if attr == :required_gold
  r.check_has_alliance if attr == :has_alliance
end
+8

. - , , . rails, .

. , , - before_create, .

model.rb

before_create :check_gold_validation

def check_gold_validation
    validate :check_gold
end 

def check_gold
   errors.add_to_base "Some Error" if self.some_condition?
end
0

, before_create. " , ". ( : http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html).

, :

before_create :check_gold

# other methods go here

private # validations don't need to be called outside the model

def check_gold
  # do your validation magic here
end

, , FYI before_save :

before_save :check_gold_levels

# other methods

private
def check_gold_levels
  initialize_gold_level if new? # this will be done only on creation (i.e. if this model instance hasn't been persisted in the database yet)
  verify_gold_level # this happens on every save
end

More about the "new"? see http://api.rubyonrails.org/classes/ActiveResource/Base.html#method-i-new%3F

0
source

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


All Articles