I'm a rails beginner (I think I have the basics down pretty well at this point), and I'm working on an app with a simple parent-child structure: Company => Client => Group => Order. The relevant DB tables for this question are Group and Order (Group has_many Orders).
Right now, when I create a new group, one of the text fields on the form is 'Order Quantity' (which is a :size attribute in the Group model), and there is a line of code in the Create action for GroupsController that generates n blank orders that belong to that particular group:
if @group.save
@group.size.times do
Order.create(:group_id => @group.id)
end
This works fine, but I want Order.id to be a decimal number rather than an integer. I tried generating the following migration:
class ChangeOrderIdToDecimal < ActiveRecord::Migration
def up
change_column :orders, :id, :decimal, :precision => 5, :scale => 4
end
which, at first, seemed to do what I wanted. All the existing orders changed from 4, 5, 6 to 4.0, 5.0, 6.0. What I ultimately want to do, though, is to add some code to the Create action in GroupsController like this:
if @group.save
order_id_decimal = 0.001
@group.size.times do
order_id = "#{@group.id}.#{order_id_decimal}".to_f
Order.create(:group_id => @group.id, :id => order_id)
order_id_decimal += 0.001
end
The idea being, if the Group ID was 75, then the orders in that Group would have ID's 75.001, 75.002, 75.003, etc.
For some reason, though, when I create new groups, it tries to save every order id as 0.0000 and gives me this error:
ActiveRecord::RecordNotUnique in GroupsController#create
Mysql2::Error: Duplicate entry '0.0000' for key 'PRIMARY': INSERT INTO `orders`
(`created_at`, `group_id`, `note`, `order_status`, `title`, `updated_at`, ) VALUES
('2012-03-04 20:28:15', 20, NULL, NULL, NULL, '2012-03-04 20:28:15')
I've tried manually changing an Order's ID from the rails console, and it saves without giving me errors, but it doesn't actually save. If I type Order.find(0.0) it pulls up the one order I just changed and it has 0.0 for ID. I'm completely baffled by this, and I haven't been able to find any help from googling it. Anyone have any ideas?