Syafiq Kamarul Azman
Syafiq Kamarul Azman

Reputation: 862

Rails range validation with data from another model

I have a Ticket and Event model in which the relationship is that an Event has many Tickets. The Ticket model has columns serial starting value and serial ending value which denotes the range of the valid serial nubers for that event.

I want to validate the Ticket on creation so that if a Ticket is created with a serial number beyond that range, the system will spew out errors saying that the range in invalid.

What I currently have in my ticket model validation is another validation to show a valid serial number for all events which is between 140000 and 149999

validates  :serial_number,
            presence: true,
            numericality: { 
                only_integer: true, 
                :greater_than_or_equal_to => 140000,
                :less_than => 149999, 
                :message => "is invalid" },
            :uniqueness => { :message => "%{value} has already been taken" }

I need to get data from the Event model and place it into the Ticket validation. Does Rails allow something like this in the model? Should I do it in the controller?

Upvotes: 1

Views: 705

Answers (2)

awendt
awendt

Reputation: 13653

Definitely do this in your model. Use custom validations for it:

validate :serial_number_valid

def serial_number_valid
  unless event.serial_number_range.include?(serial_number)
    errors.add(:serial_number, "must be within range")
  end
end

Upvotes: 3

TarunJadhwani
TarunJadhwani

Reputation: 1161

One way to do this is by using rails validation helper of inclusion. This helper validates that the attributes' values are included in a given set. For this particular case you can use:

validates :serial_number, inclusion: { in: 140000..149999 }, presence: true, uniqueness: true

If you want to use the same method in rails 4 way here's a link to that.

Upvotes: 0

Related Questions