我有一个小论坛。我有模特论坛,主题,帖子。 我想在每个论坛上展示最新主题。
这是我的模特
class Forum < ActiveRecord::Base
has_many :topics
end
class Topic < ActiveRecord::Base
belongs_to :forum
end
def index
@forums = Forum.all
@topics = Topic.all
@topic = @topics.last_topics
end
- @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
答案 0 :(得分:0)
您需要在topics
和forums
之间使用association:
#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 %>
答案 1 :(得分:0)
根据has_many relationship 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