【问题标题】:is there better way to count for three level nested forms有没有更好的方法来计算三层嵌套表单
【发布时间】:2010-01-11 13:39:24
【问题描述】:

我有一个嵌套表单,例如:

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

现在,我想知道 house.id = 1 总共有多少房间和电视。

在我给的houses_controller中

@houses = House.all

获取每栋房屋的房间数非常简单

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

我的问题是如何获得电视数量?我现在正在使用这个

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

它有效,但我不确定这是否好。 有没有更好的获取方式?

【问题讨论】:

    标签: ruby-on-rails nested nested-forms


    【解决方案1】:

    我会在模型中放置一个方法,尽量避免视图中的代码。

    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
    

    另外,如果您在控制器中加载所有 House 的对象,之后您将需要 Rooms 对象,您应该像以下方式加载房屋:

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

    这样您将进行 1 次查询,您的方法将有 1 + N_rooms + N_tvs 查询

    【讨论】:

      猜你喜欢
      • 2017-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-11-21
      • 1970-01-01
      • 1970-01-01
      • 2013-08-04
      • 1970-01-01
      相关资源
      最近更新 更多