1

在使用 STI 时,我试图获取特定 :type 的所有页面。

我在 pages_controller.rb 中有一个主类

class PagesController < ApplicationController

  def index
    @pages = Page.all
  end

end

在此之下,我在 pages_controller.rb 中有另一个类

class Blog < Page

    def index
        @pages = Blog.all   
    end

end

Blog 类不应该获取所有具有“博客”类型的页面吗?相反,无论类型如何,它都会获取所有页面。我也试过@pages = Page.where(:type => "Blog")我正在访问 URL http://localhost:3000/blog

这是我的路线

    resources :pages do
        collection do
            get :gallery
            get :list
        end     
    end
    resources :blog, :controller => :pages
4

1 回答 1

1

您需要为app/models目录中的每种类型定义一个类:

# app/models/page.rb
class Page < ActiveRecord::Base
end

# app/models/blog.rb
class Blog < Page
end

如果您希望一个控制器同时获得它们:

if blog? # implement this method yourself
  @blogs = Blog.all
else
  @pages = Page.all
end

所以本质上,all-方法返回你调用它的类的实例。

但是:我建议您为每种类型使用单独的控制器。它们是不同的资源,应该这样处理。使用InheritedResources 之类的工具来干掉你的控制器。

于 2010-12-11T10:58:42.560 回答