0

I have two linked models (simplified) :

Ad :

class Ad < ActiveRecord::Base
has_many :propositions
validates :pricemin
validates :pricemax
...

Proposition :

class Proposition < ActiveRecord::Base
belongs_to :ad
attr_accessible :price_proposition
...

I'm trying to add a restriction for the price_proposition (in "proposition" model) to be between "pricemin" and "pricemax".

How could I do that ?

Thanks for your help

2

1 Answer 1

1

Client side validation via Javascript is definitely one way to go. But if you want to do server side validation, you can do something like this:

class Proposition < ActiveRecord::Base

  belongs_to :ad
  attr_accessible :price_proposition

  validate :price_proposition_in_range

  def price_proposition_in_range
    pricemin = self.ad.pricemin
    pricemax = self.ad.pricemax
    if self.price_proposition < pricemin || self.price_proposition > pricemax
      errors.add(:price_proposition, "Must be between #{pricemin} and #{pricemax}")
    end
  end

  .
  .
  .
end

And of course, you can add further checks in the method, depending on whether you want to allow blank or not etc etc.

Sign up to request clarification or add additional context in comments.

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.