I have 2 models: vacancy and vacancy_schedule
Vacancy has_many :vacancy_schedules
Vacancy_schedule belongs_to :vacancy
In my vacancy_schedule I want to save vacancy_id, start_date, end_date, start_time, end_time
I've looked a bit into nested forms and I thought about doing it with a nested form:
class Vacancy < ActiveRecord::Base
has_many :vacancy_schedueles
accepts_nested_attributes_for :vacancy_schedueles
end
But how would I display this in my view?
I want to be able to press a + button and keep adding dates underneath each other.
My guess for only adding 1 date to the other model I would have to do something like this:
<%= f.simple_fields_for :vacancyscheduele do |t| %>
<%= t.input :start_date, :as => :date_picker, :label => false%>
<%= t.input :end_date, :as => :date_picker, :label => false%>
<%= t.input :end_hour %>
<%= t.input :end_hour %>
<% end %>
But I wouldn't know where to start when I would want to add a + sign and suddenly show a second simple_fields_for where the user can enter a next date.
And when he presses submit it all submits at the same time or when he deletes one of the dates it gets removed correctly.
The end result should be something like this in the vacancy_schedule:
Vacancy_id / start_date / end_date / start_time / end_time
1 / 1/1/2015 / 2/1/2015 / 14:30 / 19:30
1 / 5/1/2015 / 6/1/2015 / 11:30 / 12:30
1 / 10/1/2015 / 11/1/2015 / 16:30 / 19:30
2 / 6/1/2015 / 7/1/2015 / 14:30 / 19:30
etc etc
Any help or tips would be greatly appreciated.
Use the below code:
Create a file date_format.rb in config/initializers & write the following code:
class ActiveSupport::TimeWithZone
def as_date(options = {})
strftime('%m-%d-%Y')
end
def as_time(options = {})
strftime('%I:%M')
end
end
In the view , write the following code:
<%= f.simple_fields_for :vacancyscheduele do |t| %>
<%= t.start_date.as_date %>
<%= t.end_date.as_date %>
<%= t.start_hour.as_time %>
<%= t.end_hour.as_time %>
<% end %>