views:

40

answers:

1

I have a nested forms like:

class House < ActiveRecord::Base
  has_many :rooms
  accepts_nested_attributes_for :rooms
  attr_accessible :rooms_attributes
end

class Room < ActiveRecord::Base 
  has_one :tv
  accepts_nested_attributes_for :tv
  attr_accessible :tv_attributes
end

class Tv 
  belongs_to :user
  attr_accessible :manufacturer
  validates_presence_of :user
end

Now, I want to know for house.id = 1 how many rooms and tvs totally.

In the houses_controller I gave

@houses = House.all

And it's quit simple to get the room count for each house like

<% for house in @houses %>
<%= house.rooms.count %>
<% end -%>

My question is how to get tvs count? I am using this now

<%= house.rooms.map {|room| room.tvs.count}.sum %>

It works, but I am not sure this is good or not. Is there any better way to get it?

A: 

I'd put a method in the model, trying to avoid code in the views.

class House
  ...
  def tvs
    rooms.inject(0) {|r, t| t + r.tvs }
  end
end

class Room
  ...
  def tvs
    tv ? 1 : 0 # it's has_one association right now
  end
end

Also, if in your controller your are loading all House's objects, and after that you are going to need the Rooms objects, you should load the houses like:

House.find :all, :include => { :rooms => :tv }

This way you are going to do 1 query, with your approach there will be 1 + N_rooms + N_tvs queries

blaxter