我有个小论坛。我有模特论坛,主题,帖子。我想在每个论坛上展示最后一个话题。
这是我的模特
app/models/forum.rb
class Forum < ActiveRecord::Base
has_many :topics
endapp/models/topic.rb
class Topic < ActiveRecord::Base
belongs_to :forum
endapp/控制器/论坛_控制器。
def index
@forums = Forum.all
@topics = Topic.all
@topic = @topics.last_topics
endapp/views/论坛/index.html.slm
- @forums.each do |forum|
tr.dotted
td.yach
= image_tag('forumico.png')
u = link_to forum.name, forum_path(forum)
br
p = forum.desc
td = forum.topics.count
td = forum.views_count
td
= distance_of_time_in_words_to_now forum.updated_at
| назад
- @topic.each do |topic|
= topic.name
td 在浏览器上我看到每个论坛的最后一个话题.
示例:
Forum_list Last_topic
Forum_name 1 topic#9
Forum_name 2 topic#9
Forum_name 3 topic#9我想要的:
Forum_list Last_topic
Forum_name 1 topic#9
Forum_name 2 topic#23
Forum_name 3 topic#76该怎么做呢?Thx
发布于 2015-10-29 13:23:09
根据has_many关系,forum.topics得到了特定主题的所有主题,forum.topics.last.name得到了最后一个主题的名称。
- @forums.each do |forum|
tr.dotted
td.yach
= image_tag('forumico.png')
u = link_to forum.name, forum_path(forum)
br
p = forum.desc
td = forum.topics.count
td = forum.views_count
td
= distance_of_time_in_words_to_now forum.updated_at
| назад
- forum.topics.last.name if forum.topics.any?
td 发布于 2015-10-29 12:58:39
您需要在协会和topics之间使用forums
#app/models/forum.rb
class Forum < ActiveRecord::Base
has_many :topics
end
#app/models/topic.rb
class Topic < ActiveRecord::Base
belongs_to :forum
scope :latest, ->(limit = 1) { order(created_at: :desc).limit(limit) }
end这样,您可以调用以下命令:
#app/controllers/forums_controller.rb
class ForumsController < ApplicationController
def index
@forums = Forum.all
end
end
#app/views/forums/index.html.erb
<% @forum.each do |forum| %>
<% forum.topics.latest do |topic| %>
<%= topic.title %>
<% end %>
<% end %>https://stackoverflow.com/questions/33414787
复制相似问题