开发者

How can use rails polymorphic for objects that actually have fields?

Let's say I have a User model and I want to have different user roles. In a single application, you can simple store the role a string, or as another model and that's fine.

But what if you want to store more associations for the individual models? For example, let's say Admins contain links to collections and belongs to many collections that regular users should not be associated to? In fact, other users will be linked to a whole other set of models that Admins do not have.开发者_开发问答

Do we put all of the associations in the User object and just ignore them based on the type of the user? Or do we start subclassing User (like in Hibernate) to only contain the associations and model logic for that user type?

What is the way to do this in rails? Thanks!


I would suggest using Rails Single Table Inheritance. Essentially, you'll have a users table in your database, and a root User model. Multiple models (one for each "role") can inherit from User, and have their own associations:

# Regular users have no associations
class User < ActiveRecord::Base
end

# Admins have collections and notes
class Admin < User
  has_many :collections
  has_many :notes
end

# Editors only have notes
class Editor < User
  has_many :notes
end
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜