如果某些子类缺少模板,rails 会重定向到超类的模板

发布于 2024-10-03 02:59:34 字数 178 浏览 8 评论 0原文

我正在 Rails 项目中使用单表继承。我想知道是否可以通过在超类中实现某些通用函数来在子类之间共享它们的功能。

是否也可以回收超类的视图?或者我应该为常用功能编写新视图?这不会很干。 DRY 方法是什么?我应该编辑routes.rb还是有其他方法可以动态完成此任务?

最好的, E.

I am using Single-Table-Inheritance for a rails project. And I was wondering if it were possible to share functionality for some common functions between subclasses by implementing them in the superclass.

Is it possible to recycle the views of the superclass as well? Or should I write new views for the common functions? This wouldn't be very DRY. What were the DRY approach? Should I edit the routes.rb or is there another way to dynamically accomplish this?

Best,
E.

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

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

发布评论

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

评论(1

傻比既视感 2024-10-10 02:59:34

首先,您绝对可以通过在超类级别实现来在子类之间共享功能 - 这是 STI 的一大吸引力。

至于视图问题:我假设我们正在讨论对模型进行子类化,而不是对控制器进行子类化。在这种情况下,主模型的单个控制器(具有普通视图)通常适用于所有子类。不过,在表单和创建/编辑方面存在一些稍微棘手的问题。特别是,您需要从参数中提取模型的子类,并在更新其他所有内容后添加它。例如:

def create
  citation_class = params[:citation].try(:delete, :type)
  @citation = citations.new(params[:citation])
  @citation.type = citation_class
  flash[:notice] = 'Citation was successfully created.' if @citation.save

  respond_with @citation
end

First, you can definitely share functionality between subclasses by implementing at the superclass level - that's one of the big draws for STI.

As for the view question: I assume we are talking about subclassing a model, not a controller. In that case, a single controller (with normal views) for the main model will usually work fine for all of the subclasses. There are some slightly tricky issues when it comes to the forms, and creation/editing though. In particular, you will need to pull out the subclass of the model from the parameters and add it after updating everything else. For example:

def create
  citation_class = params[:citation].try(:delete, :type)
  @citation = citations.new(params[:citation])
  @citation.type = citation_class
  flash[:notice] = 'Citation was successfully created.' if @citation.save

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