开发者

Rails Model Validation on :symbol for a date

I'm trying to compare a couple of dates from my form.

Im my validation I have something like:

:mydate - 1.day

But I get:

undefined method `-' for 开发者_运维知识库:mydate:Symbol"

Totally a newb question, but I cant figure it out LOL - how do I perform date math on a symbol?

Edit:

OK, so I cant access the params from the controller either, or the form object. I'm using basic restful controllers:

def create

 @booking = Booking.new(params[:booking])

 etc...
end

and then in my model I want to validate some dates - the end result should be that a Checkin date should be the same as a Checkout date minus the number of nights

So my model:

class Booking < ActiveRecord::Base

  def validate   
    errors.add_to_base "Nights Borked" if :checkin != (:checkout - :nights.day)
  end
end

Or I'd like to do something like that but cant.

If I try and access @booking.checkin I get:

undefined method `checkin'

If I try to do

@foo = params[:booking][:checkin]

I get

undefined local variable or method `params' for #<Class:0x103fd1408>

What am I missing here. Something obvious probably lol :)


You can't perform date math on a symbol, because a symbol is merely a more-sophisticated string. It'd not holding a value other than its name. But assuming you have a model with an attribute called mydate:

@object.mydate - 1.day

or if you have a parameter passed in from a form:

params[:mydate] - 1.day

Given your updated code samples, you want to call attributes as self.attribute, like so:

class Booking < ActiveRecord::Base

  def validate   
    errors.add_to_base "Nights Borked" if self.checkin != (self.checkout - self.nights.day)
  end
end

The validate method is being called on a booking object already, so you want to call the attributes in that context.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜