def index如何查找forum_id

时间:2015-10-29 12:51:03

标签: ruby-on-rails controller

我有一个小论坛。我有模特论坛,主题,帖子。 我想在每个论坛上展示最新主题。

这是我的模特

的应用程序/模型/ forum.rb

class Forum < ActiveRecord::Base
 has_many :topics
end

的应用程序/模型/ topic.rb

class Topic < ActiveRecord::Base
 belongs_to :forum
end

的应用程序/控制器/ forum_controller.rb

def index
    @forums = Forum.all
    @topics = Topic.all
    @topic = @topics.last_topics
end

的应用程序/视图/论坛/ index.html.slim

- @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

2 个答案:

答案 0 :(得分:0)

您需要在topicsforums之间使用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