Rails - 主类,子类,如何获取子类的所有记录

发布于 2024-10-07 06:48:09 字数 761 浏览 0 评论 0原文

在使用 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 类不应该获取所有带有:type 为“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

In using STI, I'm trying to get all pages of a specific :type.

I have a main class in pages_controller.rb

class PagesController < ApplicationController

  def index
    @pages = Page.all
  end

end

Below that, I have another class in pages_controller.rb

class Blog < Page

    def index
        @pages = Blog.all   
    end

end

Shouldn't the Blog class get all pages with a :type of "Blog"? Instead it is getting all pages regardless of the type. I've also tried @pages = Page.where(:type => "Blog") I'm accessing the URL http://localhost:3000/blog

Here are my routes

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

夜雨飘雪 2024-10-14 06:48:09

您需要为 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 这样的工具来耗尽你的控制器。

You need to define a class for every type in app/models directory:

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

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

If you want one controller to get them both:

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

So in essence, the all-method returns instances of the class you called it on.

However: I would recommend you to use separate controller for each type. They are different resources and should be treaded as such. Use tools like InheritedResources to dry up your controllers.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文