How can I invalidate a rail model

I have a product model from a unique product. Therefore, when the user bought this model, no one can buy it again, and the seller cannot buy the same person as the buyer.

When I buy a product, I call the product.buy (buyer) method. But this method should invalidate the model when buyer = seller and date.sale! = Nil. But that does not work. How can i fix this?

   def buy(buyer)
    if self.user != buyer

      if self.date_sale.nil? 
        self.date_sale = Time.now
        self.buyer = buyer
      else
        # self.errors.add(:buyer, "article bougth") # Dont't work
      end             
    else
       # self.errors.add(:buyer, "seller can not buyer") # Dont't work
    end  
  end
+1
source share
2 answers

To handle nil date_sale, add this on top of your model:

validate_presence_of :date_sale

To check if there is a buyer! = Seller, you could do

validate :buyer_is_not_seller

def buyer_is_not_seller
  errors.add(:buyer, "shouldn't be seller") if buyer.id == seller.id
end
+5
source

Validation contents may work:

class Domain
  validates_presence_of :name, on: :renew
end

domain = Domain.new
domain.valid?(:renew) # false

http://api.rubyonrails.org/classes/ActiveModel/Validations.html#method-i-valid-3F

0

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


All Articles