I have a form for my model @gig. I am trying to create multiple gigs at once with the same attributes apart from date which should be picked from an array.
So far only the last date in the array and only one record is getting saved.
_form.html.erb
<%= simple_form_for @gig , url: gigs_path do |form| %>
<div class="create-title">
<%= form.input :title, label: t('gig.title'), placeholder: t('placeholder.title') %>
</div>
bla... bla... bla....
<p><%= t('gig.date') %> </p>
<% if !mobile_device? %>
<%= form.input :date, as: :string, label: false, placeholder: t('placeholder.date'), multiple: true %>
<% else %>
bla... bla... bla....
<% end %>
gig_controler.rb
def create
@gigdates = params[:gig][:date].split(';')
puts @gigdates.count
@gigdates.each do |date|
puts date
@gig = Gig.create(gig_params)
@gig.date = date
end
if @gig.save
redirect_to @gig
else
Rails.logger.info(@gig.errors.inspect)
render 'new'
end
end
def gig_params
params.require(:gig).permit(:title, :location, :description, :date, :salary, :salary_cents, :salary_currency, :genre_ids => [])
end
Using puts date in the controller, I can see that my dates are getting separated correctly.
The server shows ROLLBACK is called as many times as there are dates in the array and then the final gig saves correctly.
Update 1:
I have changed the controller which allows the creation of multiple records, I am just worried about the lack of redirects or messages if a record fails to save.
def create
@gigdates = params[:gig][:date].split(';')
@gigdates.each do |date|
@gig = Gig.new(gig_params)
@gig.date = date
@genres = Genre.where(:id => params[:choose_genres])
@gig.genres << @genres
@gig.save
end
redirect_to @gig
end