Rails partial dates -
my table has release_date column saves in format
2002-02-01
in model have
validates_date :release_date, :allow_blank => true
in new view have following
<%= f.label :release_date, class: "control-label" %> <%= f.date_select :release_date, :start_year => date.current.year, :end_year => 1970, :include_blank => true %>
with gives 3 separate drop downs selecting date.
what want partial date selectable when user knows year, or month , year. thought might work appropriate allow_blank tags in doesn't if select , month , year leave day blank doesn't save date db @ all.
how can allow partial dates? preferably saving same format used existing data isn't invalid.
in show view call release_date this
<%= @miniature.release_date.strftime("%d %b %y") unless @miniature.release_date.blank? %>
i able display whole date when available , if not have appear
feb 2002
or
2002
where that's available.
i guess release_date
should date
column, means full-date required creating record year or year+month given.
you may need integer column, date_mask
example, tell parts(year, month, day) available , modify create
action in controller store date_mask
information.
class mycontroller < applicationcontroller def create #... if params[:my_model][:"release_date(2i)"] == '' # no month given, insert fake month , day params[:my_model][:"release_date(2i)"] = '1' params[:my_model][:"release_date(3i)"] = '1' mask = 4 # 100 elsif params[:my_model][:"release_date(3i)"] == '' # no day given, insert fake day params[:my_model][:"release_date(3i)"] = '1' mask = 6 # 110 else # full-date mask = 7 # 111 end # ... mymodel.create(my_model_params.merge(date_mask: mask)) # ... end private def my_model_params params.require(:my_model).permit(:release_date, :date_mask) end end
in model, create method release_date_display
show date according release_date
, date_mask
class mymodel < activerecord::base #... def release_date_display if self.date_mask == 4 return self.release_date.strftime('%y') elsif self.date_mask == 6 return self.release_date.strftime('%b %y') else return self.release_date.strftime('%f') end end #... end
for existing data, insert 7 in data_mask
column.
update:
an example handle partial date: https://github.com/sibevin/partial-date-app
Comments
Post a Comment