Combining data into 1 model attribute

I have a calendar system in which the user enters the date and time for the event in a separate text field. I store the date and time in one attribute (start) in the event model. I find it difficult to determine how to combine date and time input and combine it in the begin attribute.

I prefer to do this with a virtual attribute ( :date and :time ), so I can easily match my form with these virtual attributes without having to do anything in the controller.

Thank you very much

+4
source share
4 answers

You can create your own access methods for date and time attributes, for example:

 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 
+10
source

You must use before_validation callback to combine the 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 logic for combining two values.

Then you should write some attr_accessor methods to get individual values ​​if necessary. To make a split and return the corresponding value.

+1
source

I think that you have a date and time field in your model, the rails allow you to read the part and time parts of the date separately in your forms (easily), and then simply combine them easily into the ONE date field. This works on purpose if your attribute is a date-time.

 # model post.rb attr_accessible :published_on # just added here to show you that it accessible # form <%= form_for(@post) do |f| %> <%= f.date_select :published_on %> <%= f.time_select :published_on, :ignore_date => true %> <% end %> 

The date picker will provide you with the publish_on date part. The selector string will give you the publish_on time part .: ignore_date => true ensures that the time picker does not display 3 hidden fields associated with publish_at, since you are already reading them in the previous line.

On the server side, date and time fields will be added!

If you, however, read the date as a text field, then this solution does not work, unfortunately. Since you are not using a composite attribute that provides rails for the built-in datetime.

In short, if you use date_select, time_select, the rails make things easier, otherwise you can look for other parameters.

+1
source

You should use the open source data collector widget that handles this for you, and not create the fields as a text field.

0
source

All Articles