1

I have a product model from an unique product. So when a user bought this model nobody can buy it again and the seller can not the same person then the buyer.

When I will buy the product I call the method product.buy(buyer). But this method should make the model invalid when the buyer = seller and date.sale != nil. But this doesn't work. How can I fix it?

   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

2 Answers 2

5

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

validate_presence_of :date_sale

To check if 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
Sign up to request clarification or add additional context in comments.

2 Comments

minor typo: validate :buyer_is_not_seller
Hello,thank you but i need this validation only when a user execute the buy method. I check with _date_sale that the article is sold. When i check every time that date_sale != nil, means this that every article is sold.
0

Validation content might 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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.