[英]How can i get the last user who created the last topic
i have 3 models as shown below. 我有3个型号,如下所示。 In my categories/index.erb.haml I have all the categories showing.
在我的category / index.erb.haml中,显示了所有类别。 I have a column that i want to show the latest topic that a user created and their name as well.
我有一列想要显示用户创建的最新主题及其名称。 I have an example below.
我下面有一个例子。
Category
has_many :topics
Topic
belongs_to :category
belongs_to :user
User
has_many :topics
.categories
- @categories.each do |category|
.container
.row
.col-md-6
.col-md-3
.img
= image_tag('first.png')
.col-md-9
%h4.category.name
= link_to category.name, category_path(category)
%p
= category.description
.col-md-2
.topic-count
%h1
= category.topics.count
.topics
Topics
.col-md-4
.description
%p
Last topic by 'user name here' Tue Nov 28, 2015
'topic title here'
According to the associations you posted, you should be able to get the user of the last topic by this: 根据您发布的关联,您应该可以通过以下方式吸引上一个主题的用户:
Topic.last.user
Also, mentioned by @marczking in the comment section. 另外,@ marczking在评论部分中也提到过。
Topic.last
will give you the last topic that was created and then Topic.last.user
will give you the corresponding user as your Topic
model belongs_to a User
. Topic.last
将为您提供创建的最后一个主题,然后Topic.last.user
将为您提供相应的用户,因为Topic
模型属于一个User
。 In order to make this work, you also need to have a user_id
column in the topics
table in the database. 为了使此工作有效,您还需要在数据库的
topics
表中有一个user_id
列。
If you want to get the last Topic
for each Category
than you have to loop through the Categories
and get the last Topic
since you have a relation. 如果要获得每个
Category
的最后一个Topic
,则必须遍历Categories
并获得最后一个Topic
因为您有关系。
Category.includes(:topics).find_each do |category|
last_topic_of_the_category = category.topics.last # <= The last topic
end
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.