Pieter Eerlings
Pieter Eerlings

Reputation: 43

rails question: how to create multiple child objects linked to a parent object with a select drop down in the parents create form?

In a booking engine for buying tickets for events, written in rails, I have the following models:

an order

a ticket

One order has many tickets, and one ticket belongs to an event.

People that want to book tickets for an event, typically create a new order. They fill in some details (kept in the order model), and at the end they see some drop downs where they can select the number of tickets for each ticket type (for example: VIP tickets, student tickets, ...).

a screenshot can be found here:

http://eerlings.com/orders.png

I would like to implement that when the order is created in the DB, for each ticket type, there is a ticket created in the DB, linked to this order. If the attendee selected "5" in the drop down for the VIP tickets, and "3" for the student tickets, there should be 8 tickets created in the DB in total.

What would be the best way to implement this in rails? any suggestions?

Ciao, Pieter

Upvotes: 1

Views: 1391

Answers (2)

Adam Stegman
Adam Stegman

Reputation: 1013

You'd probably have separate params for VIP tickets and student tickets, something like

params = {
          :num_vip_tickets => 5,
          :vip_ticket => {
                          :event_id => 1,
                          :price => 250
                         },
          :num_student_tickets => 3,
          :student_ticket => {
                              :event_id => 1,
                              :price => 10
                             }
         }

I would handle that in the controller. For instance, using some assumed names:

if params[:num_vip_tickets]
  params[:num_vip_tickets].to_i.times {@order.tickets.create params[:vip_ticket]}
end

Another way would be

class Order < ActiveRecord::Base
  has_many :tickets
  accepts_nested_attributes_for :tickets
end

class OrdersController < ApplicationController
  def create
    params[:order][:ticket_attributes] = []
    num_student_tickets = params[:num_student_tickets].to_i
    if num_student_tickets > 0
      params[:order][:tickets_attributes] += [params[:student_ticket]] * num_student_tickets
    end
    num_vip_tickets = params[:num_vip_tickets].to_i
    if num_vip_tickets > 0
      params[:order][:tickets_attributes] += [params[:vip_ticket]] * num_vip_tickets
    end
    @order = Order.new params[:order]
    # ... etc ...
  end
end

Upvotes: 1

Amala
Amala

Reputation: 1748

See this question: how to have linked drop downs in a rails form

Upvotes: 0

Related Questions