On Sep 19, 2009, at 5:35 PM, Fidel Viegas wrote:
> Hi all,
>
> I am implementing a simple invoice system where I have invoiceLines,
> and where I want to keep the order of the lines. I have tried to
> google around but have not found any sample on this.
>
> Can someone give me a pointer to something that uses a set where the
> order is kept?
>
> Thanks in advance.
>
> Regards,
>
> Fidel.


Well, that would be an Array. Or in the likely case that your data is  
accessed with ActiveRecord models, an AssociationProxy that will  
behave mostly like an Array.  You will probably find something like  
the following in any reasonable discussion about the has_many/ 
belongs_to associations. If you don't specify a default order for the  
association, then you'll get the invoice_lines back in whatever order  
the database prefers (often the order in which the database records  
were created).

## Models
class Invoice < ActiveRecord::Base
   has_many :invoice_lines, :order => 'line_number'
end
class InvoiceLine < ActiveRecord::Base
   belongs_to :invoice
end

## migration (schema)
create_table :invoices do |t|
   t.integer :number
   t.date    :inv_date
   t.date    :due_date
   # etc.
end

create_table :invoice_lines do |t|
   t.references :invoice
   # equiv. to  t.integer :invoice_id
   t.integer    :line_number
   t.string     :sku
   t.integer    :quantity
   t.decimal    :unit_price, :precision => 8, :scale => 2
   # etc.
end

## use in a controller

@invoice = Invoice.find_by_number(params[:invoice][:number])

@invoice.invoice_lines
#=> an array-like set of InvoiceLine records

-Rob

Rob Biedenharn          http://agileconsultingllc.com
[email protected]



--~--~---------~--~----~------------~-------~--~----~
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected]
To unsubscribe from this group, send email to 
[email protected]
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en
-~----------~----~----~----~------~----~------~--~---

Reply via email to