Ruby on rails 需要帮助了解ActiveRecord的工作原理吗
以下面的基本论坛为例Ruby on rails 需要帮助了解ActiveRecord的工作原理吗,ruby-on-rails,ruby,ruby-on-rails-3,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 < ActiveRec
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
到目前为止是这样吗?但是假设我还想获取发布最后一篇文章的用户信息。我的post表有一个“user\u id”列,我可以使用它。我是否需要像上一篇文章那样建立一种“有一个”的关系?这似乎不起作用:
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
请注意,我使用最后一个用户id获取用户信息。如何使用rails实现这一点?目标是使以下变量可用于在视图中呈现最后的帖子信息
forum.last_post.date # the last post object
forum.last_poster.username # the user object who created the last post
我是否理解这是如何正确工作的,我做错了什么?我想说,论坛模型上的最后一张海报似乎是必要的。因为只有一个,所以当我在视图中调用该信息时,我可能会让它慢慢加载 因此,当您在视图中工作时,只需执行forum.last_post.user.username
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
forum.last_post.date # the last post object
forum.last_poster.username # the user object who created the last post