views:

35

answers:

1

Hello,

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

+1  A: 

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
Cratchitimo
But the data for the purchase and sponsor is not in the posts object .. The data comes like this:{[:post]=>{id="5",[:repost]=>{purchase="30"},[:sponsor]=>{purchase=>"80"}}}
Ishu
Updated to reflect this. Assuming your purchase attribute is cents.
Cratchitimo