I have a form with a nested object (customer < order), and it works except that it keeps creating a new customer record.
I d like to have it check to see if an existing customer is already present in the database (using the customer s email address to search), and if so, just attach the order to the existing record, but if not, continue creating a new customer record.
I think I have to do this by using an before_save
call in my order
model, but I don t know how to pass the form parameters (email address) in there. Is this the right approach, or is there some other way?
app/models/order.rb:
class Order < ActiveRecord::Base
belongs_to :customer
...
accepts_nested_attributes_for :customer
...
end
app/models/customer.rb:
class Customer < ActiveRecord::Base
has_many :orders
...
end
app/controllers/orders_controller.rb:
def new
@order = Order.new
@order_number = "SL-#{Time.now.to_i}"
@order.customer = Customer.new
@services_available = Service.all
end
def create
@order = Order.new params[:order]
if @order.save
flash[:notice] = Order was successfully created.
redirect_to @order
else
@order_number = "SL-#{Time.now.to_i}"
render :action => "new"
end
end
app/views/order/new.html.haml:
%h1 New order
- form_for @order do |order_form|
= error_messages_for :order
%p
= order_form.label :order_number
%br
= text_field_tag , @order_number, :disabled => true, :id => order_number_display
= order_form.hidden_field :order_number, :value => @order_number
- order_form.fields_for :customer do |customer_form|
%p
= customer_form.label :first_name
%br
= customer_form.text_field :first_name
%p
= customer_form.label :last_name
%br
= customer_form.text_field :last_name
%p
= customer_form.label :phone
%br
= customer_form.text_field :phone
%p
= customer_form.label :email
%br
= customer_form.text_field :email
%p= order_form.submit Create Order
= link_to Back , orders_path