Fields_for do not save nested parameters in rails 5.0.1
I am new to rails, although I did some basic applications and read a few tutorials, this is the first time I delved into nested attributes inside forms and using for_fields.
I've searched a lot of similar questions and read the documentation on for_fields, however my form is not saved when I use fields in my form. I tested without borders and saved them (without saving the nested DB, obviously).
What I am trying to do is simple event registration, which in turn has some attributes and a date in a separate model.
I've tried with and without checks, many different things inside strong parameters
Here are my event models:
class Event < ApplicationRecord
has_many :eventdates, dependent: :destroy
accepts_nested_attributes_for :eventdates
validates :name, :description, :city, :street, :postal_code, presence: true
end
Eventdate Model:
class Eventdate < ApplicationRecord
belongs_to :event
validates :date, :start_hour, :finish_hour, :event_id, presence: true
end
Event controller:
class EventsController < ApplicationController
def new
@event = Event.new
@event.eventdates.build
end
def create
@event = Event.new(event_params)
if @event.save
redirect_to root_url
else
render "static_pages/home"
end
end
private
def event_params
params.require(:event).permit(:name, :description, :street, :city, :postal_code, :address_number, :additional_info,
eventdates_attributes: [:id, :date, :start_hour, :finish_hour, :event_id])
end
And the form:
<%= form_for(@event, url: events_path) do |f| %>
<p>
<%= f.label :nombre %>
<%= f.text_field :name %>
</p>
<div>
<%= f.fields_for :eventdates do |eventdate_fields| %>
<%= eventdate_fields.label :fecha %>
<%= eventdate_fields.date_field :date %>
<%= eventdate_fields.label :hora_de_inicio %>
<%= eventdate_fields.time_field :start_hour %>
<%= eventdate_fields.label :hora_de_termino %>
<%= eventdate_fields.time_field :finish_hour %>
<% end %>
</div>
<p>
<%= f.label :infomaciรณn_adicional %>
<%= f.text_area :additional_info %>
</p>
<p>
<%= f.submit "Crear evento" %>
</p>
<% end %>
I'm sure this is a very basic form, but somehow refuses to save to the database at all.
source to share
In the model eventdate.rb
add optional: true
to this line:belongs_to :event
class Eventdate < ApplicationRecord
belongs_to :event, optional: true
validates :date, :start_hour, :finish_hour, :event_id, presence: true
end
As Rails will build first eventdates
and then build event
and link to them evendates
(updating everything event_id
in these evendates
). But on creation, the eventdates
column event_id
is equal nil
and eventdates
cannot be saved.
source to share