【问题标题】:Need help understanding how ActiveRecord works需要帮助了解 ActiveRecord 的工作原理
【发布时间】:2012-08-29 23:02:04
【问题描述】:

以下面的基本论坛为例。

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”关系并指定我要使用的主键,如下所示:

类论坛 :destroy has_one :last_post, :class_name => 'Post', :primary_key => :last_post_id 结束

那么我的查询将如下所示:

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

到目前为止是正确的吗?但是假设我还想获取发布最后一篇文章的用户信息。好吧,我的 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 

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

【问题讨论】:

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


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-23
      • 2016-08-28
      • 2018-10-06
      • 2013-03-21
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多