Ruby on Rails 多态关联 [英] Ruby on Rails polymorphic association

查看:36
本文介绍了Ruby on Rails 多态关联的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我想要实现的目标:我有一个用户表,每个用户可以是十几种类型中的任何一种:演员、舞者、导演……这是在注册后确定的.每种类型的用户都可以拥有任意数量的配置文件.例如.演员可以有任意数量的 actor_profiles,舞者可以有任意数量的 dancer_profiles,...

Here's what I'm trying to achieve: I have a Users table and each user can be any of a dozen of types: actor, dancer, director,...which is determined after signing up. Each type of user can have any number of profiles. Eg. actors can have any number of actor_profiles, dancers cand have any number of dancer_profiles,...

问题是我如何将个人资料与用户联系起来.一个明显的解决方案是为每个配置文件类型创建一个附加表,这样我就可以在 User 中使用一个多态的belongs_to,然后在每个配置文件中使用一个简单的belongs_to,但这似乎不是最佳的.一个可以说更好的方法是告诉 rails 用户它是 actor 类型,这样 user.profiles 会自然地工作,没有任何混乱.rails 是否支持这种行为,或者有什么比前一种方法更好的方法?谢谢.

The problem is how do I link the profile with the user. An obvious solution would be to create an aditional table for each profile type, so that I could use a polymorphic belongs_to in User and then a simple belongs_to in each profile, but that seems less than optimum. An arguably better way would be to tell rails that user it's of type actor, so that user.profiles would work naturally, without any clutter. Does rails support such behaviour, or is there anything better than the former method? Thanks.

推荐答案

pjb 的回答使用单表继承.为此,您需要将一个名为 type 的列添加到您的用户和您的 Profiles* 表中,以便 Rails 可以保存这是什么类型的用户(因为 Actor、Dancer 等只是 User 的子类).

pjb's answer uses Single Table Inheritance. For this to work you need to add a column called type to your Users and to your Profiles* tables, so that Rails can save what type of User this is (since Actor, Dancer etc. are just subclasses of User).

这意味着它们都将保存在用户/配置文件表中,但是当您实例化它们时,ActiveRecord 会将它们实例化为正确的类型.有了这个,你就可以打电话

This means they will all be saved in the users/profiles tables, but when you instantiate them ActiveRecord will instantiate them as the correct type. With this you'll be able to call

User.find

但也做类似的事情

Actor.find, Actor.all, etc

并将其范围仅限于演员

Google rails 单表继承 了解更多细节和示例.

Google rails single table inheritance for more details and examples.

  • 当然,您需要像声明 User 子类一样声明 Profile 子类

班级简介ActiveRecord::Base归属地:用户结束

class Profile < ActiveRecord::Base belongs_to :user end

class ActorProfile <轮廓结束

class ActorProfile < Profile end

class DancerProfile <轮廓结束

class DancerProfile < Profile end

这篇关于Ruby on Rails 多态关联的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆