Rails 4 - 检索关联的孙子

Rails 4 - Retrieve grandchildren on association

我在 rails 4 的论坛应用程序中遇到关联问题。这可能很简单,但我找不到解决我问题的任何解决方案(我也是 rails). 这是论坛层次结构:主题 > 主题 > Post(类似于评论)

我想要的是,在主题显示操作中,检索它自己的 posts。

在我的模型中我有

#Theme model
class Theme < ActiveRecord::Base
    has_many :topics, dependent: :destroy
    has_many :posts
end

#Topic model
class Topic < ActiveRecord::Base
    belongs_to :theme
    has_many :posts, dependent: :destroy
end

#Post model
class Post < ActiveRecord::Base
    belongs_to :theme
    belongs_to :topic
end

在我的主题和主题控制器中,我有这个(而且有效!):

#show action on Themes Controller
class ThemesController < ApplicationController
    def show 
        @theme = Theme.find(params[:id])
        @topics = @theme.topics
    end
end

#show action on topics controller
class TopicsController < ApplicationController
def show
    @theme = Theme.find(params[:theme_id])
    @topic = @theme.topics.find(params[:id])
end

这行得通,在我看来我可以展示我得到的主题和他们得到的主题。 要在主题中访问我的 posts,我正在尝试;

#still inside show action on topics controller
class TopicsController < ApplicationController
def show
    @theme = Theme.find(params[:theme_id])
    @topic = @theme.topics.find(params[:id])
    @posts = @theme.topics.posts
end

但是完全不行!我收到错误

NoMethodError in ForumTopicsController#show
undefined method `posts' for #<ForumTopic::ActiveRecord_Associations_CollectionProxy:0x007fddd8c14158>

如果我尝试创建新的 post 直接转到它的 'new action' url,它会起作用,我假设它会保存与其主题相关的 post和主题。 这是我的路线:

Rails.application.routes.draw do
resources :forum_themes do
    resources :forum_topics do
        resources :forum_posts
    end
 end

我只想在主题视图中访问我的 Posts ;-; 我尝试了一些与"collect"相关的东西,但是没有用! (也许我是那个根本不工作的人:P)

求求你帮忙!

更新

这些是我的迁移文件,不知道能不能帮上忙...

#migration file of themes
class CreateThemes < ActiveRecord::Migration
    def change
        create_table :themes do |t|
            t.string :title
            t.text :description
            t.timestamps null: false
        end
    end
end
#migration file of topics
class CreateTopics < ActiveRecord::Migration
    def change
        create_table :topics do |t|
            t.string :author
            t.string :title
            t.text :body
            t.references :theme, index: true
            t.timestamps null: false
         end
   end
end
#migration file of posts
class CreatePosts < ActiveRecord::Migration
    def change
        create_table :posts do |t|
            t.string :title
            t.text :content
            t.references :topic, index: true
            t.references :theme, index: true
            t.timestamps null: false
         end
    end
end

undefined method `posts' for ForumTopic::ActiveRecord_Associations_CollectionProxy:0x007fddd8c14158

问题出在这里@posts = @theme.topics.posts@theme.topics returns 相关主题 的所有主题,所以你不能将 posts 添加到它。

相反,您需要在如下视图中循环遍历 @theme.topics,以显示与 主题

<% @theme.topics.each do |topic| %>
  <%= topic.posts %>
<% end %>