使用 Rails 中的单表继承创建单个创建表单

发布于 2024-09-29 14:44:25 字数 694 浏览 10 评论 0原文

我在 Rails 中使用 STI,并且有一个 Vehicle 对象,它有许多不同类型的子类,如 Car、Truck 等。它适用于一个简单的应用程序,因此 STI 在这种情况下工作正常,但我无法创建可以创建任何类型的车辆记录的单一表单。

使用以下路由:

resources :vehicles
resources :cars, :controller => 'vehicles'
resources :trucks, :controller => 'vehicles'

我可以设置 /cars 和 /trucks 路由,并且两者都指向相同的表单。然而,由于表单指向车辆控制器,并为表单生成一个 Vehicle 对象,因此它无法知道 /cars url 应该创建一个 Car 对象。

我正在尝试设置一个路由系统,其中 /cars 指向一个表单,该表单本质上知道使用 Car.new 甚至 Report.new(:type => "Car") 为表单创建一个对象。我考虑过使用像 /vehicles/:subclass 这样的路由系统,并以某种方式在控制器中使用 params[:subclass] ,但我也无法弄清楚如何进行这种路由并仍然避免由 Rails 引起的其他路由错误'性传播疾病的魔力。

我总是可以解析 URL 来获取值,但这似乎是一种不安全且狡猾的方法。

我很好奇是否有人对 Rails 方法有任何建议或经验。谢谢!

I'm using STI in Rails, and I've got a Vehicle object, that has many different types of subclasses, like Car, Truck, etc. It's for a simple app, so STI works fine in this case, but I'm having trouble creating a single form where any type of Vehicle record can be created.

Using the following routing:

resources :vehicles
resources :cars, :controller => 'vehicles'
resources :trucks, :controller => 'vehicles'

I can have /cars and /trucks routing set up, and both pointing to the same form. However, since the form is pointing to the vehicles controller, and generating a Vehicle object for the form, it has no way to know that the /cars url should create a Car object.

I'm trying to get a routing system set up where /cars would point to a form that would intrinsically know to make a object for the form using either Car.new or even Report.new(:type => "Car"). I thought about working a routing system like /vehicles/:subclass, and somehow using params[:subclass] in the controller, but I also can't figure out how to do that sort of routing and still avoid other routing errors caused by Rails' STI magic.

I could always parse the URL to get the value, but that seems like an unsafe and hacky way to go about it.

I'm curious if anyone has any advice or experience on the Rails way to do this. Thanks!

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

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

发布评论

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

评论(1

仄言 2024-10-06 14:44:25

由于您想对所有车辆使用相同的表单,因此我假设除了对象类型之外的所有字段都相同。那么为什么不在表单中提供一个组合框来允许用户选择要创建的对象类型呢?

然后,您可以在控制器的创建操作中处理持久的正确对象。

Since you want to use the same form for all vehicles, then I'm assuming all the fields are the same except for the object type. Then why not have a combo box in the form to allow the user select what type of object the user want to create?

You can then handle the proper object persistent in the create action in the controller.

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