All,
I’ve just started Rails and Ruby a week or so ago. Please forgive me
for my ignorance. I started writing a small test application to test
some of my new knowledge and have hit a wall. Would like some best
practices.
I have 3 tables, as below…
CREATE TABLE carts
(
id
int(11) NOT NULL auto_increment,
name
varchar(255) NOT NULL,
quantity
int(11) NOT NULL,
PRIMARY KEY (id
)
CREATE TABLE orders
(
id
int(11) NOT NULL auto_increment,
name
varchar(255) NOT NULL,
address
varchar(255) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=2 ;
CREATE TABLE order_details
(
id
int(11) NOT NULL auto_increment,
name
varchar(255) NOT NULL,
quantity
int(11) NOT NULL,
order_id
int(11) NOT NULL,
PRIMARY KEY (id
)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=4 ;
model cart.rb
class Cart < ActiveRecord::Base
end
model order.rb
class Order < ActiveRecord::Base
has_many :order_details
end
model order_detail.rb
class OrderDetail < ActiveRecord::Base
belongs_to :order
end
In the carts table holds a shop cart with product details. For the
ease of implementation, I’ve refrained from putting relationships with
a product table or any session. Let’s just say, the field name “name”
is the product name and “quantity” holds the quantity.
What I want to do is when the order is created via a form with the
“name” and “address” fields, it will create
- The order in the order table
- Utilize the relationship in the model and update/create the
order_details from the contents of the cart table.
My question is if there is a simpler way to do the following with a
more ruby like way. I’ve read in a book that you can do a
@order.order_detail << @cart based on the code below.
Any advice is greatly appreciated.
What I’ve done in the controller is this …
order_controller.rb
class OrderController < ApplicationController
def new
end
def create
@cart = Cart.find(:all)
@order = Order.new(params[:order])
@order.save!
@cart.each do |cart|
@order_details = OrderDetail.new
@order_details.name = cart.name
@order_details.quantity = cart.quantity
@order_details.order_id = @order.id
@order_details.save!
end
end
end
view order/new.rhtml
<% form_tag :action => ‘create’ do %>
Name
<%= text_field 'order', 'name' %>
Address
<%= text_field 'order', 'address' %>
<%= submit_tag “Create” %>
<% end %>
view order/create.rhtml