计算rails中对象的孙子

时间:2010-11-25 12:48:53

标签: ruby-on-rails activerecord

您好我正在使用rails(3)构建一个小论坛应用程序。我在Rails问题上相当新,当我想拉出一个用论坛ID指定的顶板(一个属于论坛的板)时,我就陷入了困境。

“定义顶板”:属于具有最多topic_replies&的特定forum_id的板。话题。

“家谱”:论坛>董事会>主题> TopicReply

我的模特:

**forum.rb**

class Forum < ActiveRecord::Base
  default_scope :order => 'display_order ASC'
  has_many :boards, :dependent => :destroy
end


**board.rb**

class Board < ActiveRecord::Base
  default_scope :order => 'display_order ASC'

  belongs_to :forum
  has_many :topics, :dependent => :destroy
  has_many :topic_replies, :through => :topics

  def latest_topic_reply
    t = TopicReply.find_by_sql("SELECT tr.* from topic_replies tr, topics t where tr.topic_id = t.id AND t.board_id = #{self.id} ORDER BY tr.updated_at desc LIMIT 1;")[0]
  end
end


**topic.rb**

class Topic < ActiveRecord::Base
  belongs_to :board
  has_many :topic_replies, :dependent => :destroy
end


**topic_reply.rb**

class TopicReply < ActiveRecord::Base
  belongs_to :topic
end

在SQL中我会这样做:

"SELECT b.* FROM boards b,topics t WHERE t.board_id=b.id AND b.forum_id=2 GROUP BY board_id ORDER BY SUM(t.topic_replies_count) DESC LIMIT 4;"

我更喜欢用活动记录管理它(或者这不比SQL好吗?),我还不太熟悉它。有人能把我推向正确的方向吗?

提前致谢

1 个答案:

答案 0 :(得分:1)

你可以试着让它像这样工作:

Board.joins(:topics).where(:forum_id => @forum.id).order(:topic_replies_count).to_sql

通过使用to_sql,您可以看到它生成的SQL。 topic_replies_countTopic中为counter cache column,其中包含当前相关主题回复的数量。

guide中查看有关Rails 3查询的详细信息。