views:

79

answers:

1

I'm looking to create a custom validation in Rails. I need to validate that a POSTed start_date_time and end_date_time (together) do not overlap that combination in the database.

Example:

In the database:

start_date
  05/15/2000
end_date
  05/30/2000

POSTed:

start_date
  05/10/2000
end_date
  05/20/2000
FAILS!

Here's the rub:

1) I want to send both start and end fields into the function

2) I want to get the values of both POSTed fields to use in building a query.

3) Bonus: I want to use a scope (like say, for a given [:user_id, :event] -- but, again, I want that to be passed in.

How do I get the values of the fields?

Let's say my function looks like this:

def self.validates_datetime_not_overlapping(start, finish, scope_attr=[], conf={})
    config = {
        :message => 'some default message'
    }
    config.update(conf)

    # Now what?
end

I'm sort of stuck at this point. I've scoured the net, and can't figure it out.... I can get the value of either start or finish, but not both at the same time by using validate_each ...

Any help would be great!

Thanks :)

A: 

What about custom validation methods?

You can add:

validate :check_dates

def check_dates
  do.whatever.you.want.with.any.field
end

EDIT:

So maybe validate_with?

Modified example from RoR Guides:

class Person < ActiveRecord::Base
  validates_with DatesValidator, :start => :your_start_date, :stop => :your_stop_date
end

class DatesValidator < ActiveRecord::Validator
  def validate
    start = record.send(options[:start])
    stop  = record.send(options[:stop])

    ...
  end
end
klew
The trick here is that I will not know beforehand the *name* of the fields that I want to work with. I want this abstract so that I can just send the names in the validation call. Make sense?
Mr M
Validations are run when you save object and then you can't send any parameter. So I think that you want to create somethig like `validate_my_date_fields :start_date, :finish_date` that only takes two arguments and then fire some method that will check it?
klew
I may have to try this new EDIT you suggest.... I'll get back to you.(THANKS)...
Mr M
OK... Apparently this method is Rails 3. I'm on 2.3.8. IS there a way to do this with 2.3.8?Many thanks!
Mr M