Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

combining data to 1 model attribute

I have a calendar system in which the user enters date and time for an event in a seperate text_field. I store the date and time in one attribute (begin) in the Event model I have a hard time figuring out how to combine the date and time input and combine it into the begin attribute.

I preferably want to do this via a virtual attribute (:date and :time) so I can easily map my form against those virtual attributes without the need to do something in the controller.

Many thanks

like image 530
Tarscher Avatar asked Dec 17 '22 13:12

Tarscher


2 Answers

You can make your own accessor methods for the date and time attributes like this:

def date
   datetime.to_date
end

def date=(d)
  original = datetime
  self.datetime = DateTime.new(d.year, d.month, d.day,
    original.hour, original.min, original.sec)
end

def time
   datetime.to_time
end

def time=(t)
  original = datetime
  self.datetime = DateTime.new(original.year, original.month, original.day,
    t.hour, t.min, t.sec)
end
like image 167
Kris Avatar answered Jan 03 '23 15:01

Kris


You should use before_validation callback to combine data from two virtual attributes into one real attribute. For example, something like this:

before_validation(:on => :create) do
  self.begin = date + time
end

Where date + time will be your combining logic of the two values.

Then you should write some attr_accessor methods to get individual values if necessary. Which would do the split and return appropriate value.

like image 35
Syed Aslam Avatar answered Jan 03 '23 16:01

Syed Aslam