开发者

Custom Rails Validation - multiple fields simultaneously

开发者 https://www.devze.com 2023-01-13 22:00 出处:网络
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.

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
开发者_JAVA百科

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 :)


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
0

精彩评论

暂无评论...
验证码 换一张
取 消