Submitting multiple forms in Rails

I need to submit multiple forms, I followed the advice of this post: How to submit multiple repeating forms from one page in Rails - preferably with a single button

Note. I'm still new to Rails / programming and some of my ways of doing things may not be ideal.

Here's my view:

 = form_tag ([@event, @registration]) do
    - x.times do
      = render 'multi_form'
    = submit_tag "Submit registrations"

      

Form (note there are more fields):

- hidden_field_tag :event_id, :value => @event.id

.control-group
  = label_tag :title
  .controls
    = select("registrations[][title]", :registration, Registration::TITLE)

.control-group
  = label_tag :first_name
  .controls
    = text_field_tag "registrations[][first_name]"

.control-group
  = label_tag :last_name
  .controls
    = text_field_tag "registrations[][last_name]"

.control-group
  = label_tag :email
  .controls
    = text_field_tag "registrations[][email]"

      

Controller:

  def create
    array_number = 0
    x.times do
      @registration = Registration.new(params[:registrations][array_number])
      @registration.save
      UserMailer.registration_user_notify(@event, @registration).deliver
      array_number = array_number + 1
    end
    respond_to do |format|
      format.html {redirect_to thank_you_event_registrations_path(@event)}
    end
  end

      

When submitting, it seems to be somewhat of a correct solution as it sends an email to x unique email addresses, which makes me think @registration contains the correct data in every cycle - it's not a save to the database. I see that all the parameters are in the log file, except that the header seems to be doing something bad (see below: but I will stop at that later), the main thing I want to do now is every array is executed and save it as a new entry.

Magazine:

Parameters: {"utf8"=>"â", "authenticity_token"=>"BQXm5fngW27z/3Wxy9qEzu6D8/g9YQIfBL+mFKVplgE=", "event_id"=>"7", "registrations"=>[{"title"=>{"registration"=>"Mrs"}, "first_name"=>"Person", "last_name"=>"One", "email"=>"charl@privatelabel.co.za"...

      

I hope the information I have provided is sufficient, any advice would be appreciated.

Thank!

EDIT:

@iblue

This is a trick! It was a validation error and it was saving everything to different lines. Thank you very much!

One more thing, if I can, any idea of ​​how the title part of the form should be formatted for the paramater to return:

"title"=>"Mrs",

      

Unlike:

"registrations"=>[{"title"=>{"registration"=>"Mrs"},

      

Thanks again!

+2


source to share


1 answer


You are not checking if @registration.save

the record is actually being saved. It can return true

or false

. I am guessing it is just silent.



If you use @registration.save!

it will throw an exception when something goes wrong. I am guessing there is some kind of validation error in there.

0


source







All Articles