如何在 Rails 中为单表继承创建控制器?

发布于 2024-09-02 18:20:17 字数 566 浏览 7 评论 0原文

我正在设置单表继承,使用 ContactEvent 作为 ContactEmail、ContactLetter 和 ContactCall 都将继承的模型。

但我对如何创建路由和控制器感到困惑。

例如,假设我想创建一个电子邮件类型的新 ContactEvent。

我想要一种执行以下操作的方法:

new_contact_event_path(contact, email)

这将从联系人模型和电子邮件模型中获取实例。

在里面,我想 contact_event_controller 需要知道......

   @contact_event.type = (params[:email]) # get the type based on what was passed in?
   @contact_event.event_id = (params[:email]) #get the id for the correct class, in this case Email.id

只是不确定这是如何工作的......

I am setting up the Single Table Inheritance, using ContactEvent as the Model that ContactEmail, ContactLetter, and ContactCall will all inherit.

But I'm stumped on how to create the routing and the controller.

For example, let's say I want to create a new ContactEvent with type Email.

I would like a way to do the following:

new_contact_event_path(contact, email)

This would take the instance from Contact model and from Email model.

Inside, I would imagine the contact_event_controller would need to know...

   @contact_event.type = (params[:email]) # get the type based on what was passed in?
   @contact_event.event_id = (params[:email]) #get the id for the correct class, in this case Email.id

Just not sure how this works....

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

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

发布评论

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

评论(2

皓月长歌 2024-09-09 18:20:17

我有类似的问题。

请参阅这里我是如何解决的。

I had similar problem.

See here how I solved it.

无边思念无边月 2024-09-09 18:20:17

我将为您的每种资源类型提供一个控制器(也许还有视图)。因此,为 ContactEmail 添加一个控制器,为 ContactLetter 等添加一个控制器。不要为基类 ContactEvent 添加一个控制器。然后,您的路径将如下所示:

new_contact_email_path(@contact) or new_contact_letter_path(@contact)

然后,控制器操作将使用它们所代表的正确模型,即:

@contact_email = ContactEmail.new(params[...])

如果您可以将三种类型的资源分开,而不是尝试传递类型并在一个控制器中构建正确的对象你应该会发现生活变得更加轻松。缺点是您可能需要在前端有更多链接/表单/视图,但是根据您的应用程序,从用户的角度来看这可能不是一件坏事。

I would have a controller (and maybe views) for each of your resource types. So add a controller for ContactEmail one for ContactLetter etc. Don't bother with one for the base class ContactEvent. Then your paths would read something like:

new_contact_email_path(@contact) or new_contact_letter_path(@contact)

The controller actions would then use the right model for that they represent, ie:

@contact_email = ContactEmail.new(params[...])

If you can keep your three types of resources separate rather than trying to pass the type in and building the right object in one controller you should find life much easier. The downside is you may need more links/forms/views in the front end, however depending on your application that may not be a bad thing from the user's perspective.

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