需要帮助了解ActiveRecord的工作原理

时间:2012-08-29 23:02:05

标签: ruby-on-rails ruby ruby-on-rails-3

采用以下基本论坛示例。

class Forum < ActiveRecord::Base
  has_many :topics, :dependent => :destroy
end

class Topic < ActiveRecord::Base
  belongs_to :forum
  belongs_to :user
  has_many   :posts, :dependent => :destroy
end

class Post < ActiveRecord::Base
  belongs_to :topic
  belongs_to :user 
end

class User < ActiveRecord::Base
  has_many :posts
  has_many :topics
end

现在说我想添加获取每个论坛的“最后发布”信息的功能。我的论坛表有一个名为“last_post_id”的列,其中包含所述论坛中最后一篇帖子的ID。如果我理解活动记录的工作方式,我需要在论坛模型中添加“has_one”关系并指定我想要使用的主键,如下所示:

类论坛&lt;的ActiveRecord :: Base的   has_many:topics,:dependent =&gt; :破坏   has_one:last_post,:class_name =&gt; '发布',:primary_key =&gt; :last_post_id 端

然后我的查询将如下所示:

@forums = Forum.all(:include => [:last_post])

到目前为止这是对的吗?但是说我还想获取发布最后一篇文章的用户信息。那么我的帖子表有一个我可以使用的“user_id”列。我是否需要像创建last_post一样创建“has_one”关系?这似乎不起作用:

class Forum < ActiveRecord::Base
  has_many :topics, :dependent => :destroy
  has_one :last_post  , :class_name => 'Post', :primary_key => :last_post_id 
  has_one :last_poster, :class_name => 'User', :primary_key => :last_post_user_id
end

如何使用last_post.user_id的值从用户表中获取用户信息。原始查询看起来像这样:

SELECT forums.*, 
       last_post.id              as last_post_id,
       last_post.user_id         as last_post_user_id,
       last_post_user.username   as last_post_username,
  FROM forums as forums
 INNER JOIN posts  as last_post      ON last_post.id       = forums.last_post_id
 INNER JOIN users  as last_post_user ON last_post.user_id  = last_post_user.id

请注意,我使用last_post.user_id获取用户信息。你是如何使用rails的呢?目标是让以下变量可用于在视图中呈现最后的帖子信息。

forum.last_post.date       # the last post object
forum.last_poster.username # the user object who created the last post 

我是否理解这是如何正常运作的,我做错了什么?

1 个答案:

答案 0 :(得分:2)

我会说论坛模型上的last_poster似乎是必要的。因为只有一个,当我在视图中调用该信息时,我可能只是懒得加载。

因此,当您在视图中工作时,只需执行forum.last_post.user.username