开发者

Two different profile types

Let's say you have two different categories 开发者_C百科of users with different profiles: one for music artists and one for listeners. The profiles for each have some overlapping attributes, and some different attributes. Should you have separate models for each different profile? Or should you just have a binary data column in the user table for whether the user is an artist or not? How would this be structured?


You can use Single Table Inheritance, which can be achieved by creating subclasses of a model.

Generate a Profile model with a type:string column (The name can be overriden):

$ rails g model Profile type:string

Now, in profile.rb, subclass your model:

class Profile < ActiveRecord::Base
  # Common profile attributes
end

class Artist < Profile
  # Things specific to an artist profile
end

class Listener < Profile
  # Things specific to a listener profile
end

When you create an Artist or Listener, it'll be saved in the profiles table along with the type of the profile.

For example, if you do Artist.create, it'll be saved in the profiles table with type='Artist'.

When you fetch the record, it will be returned in its appropriate model, be it Artist, Listener or a generic Profile.

For more information about this technique, take a look at this question.

This blog post does a nice job explaining it as well.


One default called Profile containing the common attributes and two others (Artistic, Listener) models with the specific attributes of each one

And in the Profile, use a field to save the type (artistic or listener)

Just my opinian.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜