Ruby on rails 在rails中显示第一条记录
假设我有一个评论模型和一个帖子模型 我可以在视图中使用什么代码来显示链接帖子的第一条评论?假设:Ruby on rails 在rails中显示第一条记录,ruby-on-rails,Ruby On Rails,假设我有一个评论模型和一个帖子模型 我可以在视图中使用什么代码来显示链接帖子的第一条评论?假设: post = Post.find(params[:id]) post模型包含: has_many :comments 然后你可以: comments = post.comments first_comment = comments.first 其中123是您的帖子ID。@post.comments.first正常工作。(@post应该在您的控制器方法中设置) 不过,最好认识到“first”表示
post = Post.find(params[:id])
post模型包含:
has_many :comments
然后你可以:
comments = post.comments
first_comment = comments.first
其中123是您的帖子ID。@post.comments.first正常工作。(@post应该在您的控制器方法中设置) 不过,最好认识到“first”表示关联中的first,这通常是按id排序的。由于ids自动递增,这与“first added”或“earliest comment”相同。但也不一定是这样 如果您的注释关联指定了不同的顺序,则first将使用此选项,例如,如果您的关联看起来像这样:
has_many :comments, :order=>'rating desc'
然后(假设“评级”字段以某种方式设置为代表平均评级的某个值)post.comments.first将为您提供评级最高的评论,而不是第一个要添加的评论
在这种情况下,假设您的注释模型有时间戳,那么您需要执行以下操作
@post.comments.find(:first, :order=>'created_at asc')
对于这样一个简单的任务,这是很多不必要的变量赋值。只是为了说明processfind在默认情况下是按id进行的,而find(:first)(在编辑之前)是按id进行的。first是令人讨厌的
@post.comments.find(:first, :order=>'created_at asc')