AJBradley
AJBradley

Reputation: 185

Ruby on Rails 4 Validation

I'm relatively new to Ruby on rails, and I'm trying to validate a field. I have an Ask model which belongs to a User model. The User has a parameter account_dollars and the Ask has a parameter price. When filling in the form to create an ask, I would like to validate that the ask's price field is less than or equal to the current user's account_dollars.

Ask.rb

class Ask < ActiveRecord::Base
  belongs_to :user
  validates :user_id, presence: true
  validates :price, presence: true,
  numericality: {greater_than: 0}
end

Thanks for the help with this basic question - I don't know enough yet to properly google it.

Upvotes: 1

Views: 4433

Answers (1)

jvans
jvans

Reputation: 2915

You can write custom validations in rails, I would do something like this:

 class Ask < ActiveRecord::Base
    belongs_to :user
    validates :user_id, presence: true
    validates :price, presence: true,
    numericality: {greater_than: 0}
    validate :has_enough_dollars

    def has_enough_dollars
      if user.account_dollars < price
        errors.add_to_base("The price is larger than the user account balance")
      end
    end
  end

You can read more about rails validations here: http://edgeguides.rubyonrails.org/active_record_validations.html

Upvotes: 2

Related Questions