Hi David,
Collections should work in a has_many relationship. In my example below, the
Customer model has_many :addresses
Addresses are of the Array class
class Customer < ActiveRecord::Base
has_many :addresses
end
Customer and Address tables might look something like:
create_table "customers" do |t|
t.column "number", :string, :limit => 50
t.column "name", :string, :default => "", :null =>
false
end
create_table "addresses" do |t|
t.column "customer_id", :integer, :default => 0, :null =>
false
t.column "street", :string, :default => "", :null
=> false
t.column "city", :string, :default => "", :null =>
false
end
Some data:
insert into customers values
(1, ''10001'', ''AAA Cooper''),
(2, ''10002'', ''Absolute'');
insert into addresses values
(1, 1, ''1751 Kinsey Road'', ''Vancouver''),
(2, 1, ''101-11312-98 Avenue'', ''Grande
Prairie''),
(3, 2, ''800 Cabin Hill Dr'', ''Greensburg''),
Console testing:>ruby script\console
>>c=Customer.find(1)
=> #<Customer:0x39251f0 @attributes={"name"=>"AAA
Cooper",
"number"=>"10001", "id"=>"1",
"address_id"=>"1"}>
>>c.addresses.size
2
>>c.addresses[0].city
Vancouver
>> c.addresses.each {|x| p x.city}
Vancouver
Grand Prairie
I use collect in my rhtml templates like so:
<% for customer in @customers %>
<tr class=''altRow''>
<td><%=h customer.name %></td>
<td align=''left'' colspan=''5''
> </td>
<td> </td>
<td><%= link_to ''Show'', :action =>
''show'', :id => customer %></td>
<td><%= link_to ''Delete'', { :action =>
''destroy'', :id => customer },
:confirm => ''Are you sure?'', :post => true
%></td>
</tr>
<% for addr in customer.addresses.collect %>
<tr>
<td> </td>
<td><%=h addr.street %></td>
<td><%=h addr.city %></td>
</tr>
<%
end
end
%>
Hope this helps!
Dave
On 6/12/06, David Andersen <d@davidx.org> wrote:>
> Hey, i''m trying to iterate over the grouped results of a :group
statement,
>
> for example, like a city, has_many :buildings, :group =>
"neighbourhood"
>
> or @city.buildings.find(:group => "neighbourhood_id")
>
> or even if i were to grab it straight from sql,
>
> how do i iterate over the result ?
>
> i thought maybe it would be key value, key being the neighbourhood id
> and value being the collection, however that didnt seem to work for me.
>
> what i would like accomplish is being able to display the of buildings
> for each neighbourhood.
>
> any ideas ?
>
> thanks,
>
> d.
>
>
> _______________________________________________
> Rails mailing list
> Rails@lists.rubyonrails.org
> http://lists.rubyonrails.org/mailman/listinfo/rails
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL:
http://wrath.rubyonrails.org/pipermail/rails/attachments/20060719/cfce4875/attachment.html