Ishu
Ishu

Reputation: 638

How can I validate the data calculated on the basis of associated models

I have a posts model which has_one reposts and has_one sponsored. User can purchase reposts and sponsored posts while creating a post. I want that the minimum purchase(sum of reposts and sponsored purchases) be atleast 1$. so i want to validate this in the post model but i can't figure out on how to write such a validation rule. Here is my post model:

class Post < ActiveRecord::Base
  has_one :repost
  has_one :sponsor

Any help is more than appreciated.

Thanks

Upvotes: 2

Views: 118

Answers (1)

jmcnevin
jmcnevin

Reputation: 1285

You'll need a custom validator... this is just to give you a basic idea, since I have no idea what your model attributes actually are.

validate :minimum_purchase

protected

def minimum_purchase
  unless ((self.repost.try(:purchase).to_i + self.sponsor.try(:purchase).to_i) == 100)
    self.errors.add_to_base("You need to purchase at least $1!")
  end
end

Upvotes: 1

Related Questions