Rails: multiple "types" of one model through related models?

I have a model Userin my application in which I would like to store basic user information, such as email address, first and last name, phone number, etc.

I also have many different types of users in my system, including sales agents, customers, guests, etc.

I would like to be able to use the same model Useras the base for everyone else, so I do not need to include all fields for all related roles in one model and can delegate as needed (reduction of binary database fields, as well as ensuring easy mobility from changing one user of one type to another).

So, I would like to:

User
-- first name
-- last name
-- email
--> is a "client", so
---- client field 1
---- client field 2
---- client field 3

User
-- first name
-- last name
-- email
--> is a "sales agent", so
---- sales agent field 1
---- sales agent field 2
---- sales agent field 3

and so on...

, , , "" ( , , , , ). , wizardly. , , User (, first_name email), , (, - client client_field_1 client_field_2, User).

? , , -.

- ? ?

+3
2

, , .

(STI), , , User SalesAgent Client .. . , , - "type", ActiveRecord :

class User < ActiveRecord::Base
end

class Agent < User
end

, - . :

class User < ActiveRecord::Base
  has_one :agent_role,
    :dependent => :destroy
end

class AgentRole < ActiveRecord::Base
  belongs_to :user

   # Represents the agent-specific role fields
end

, , has_many, .

+1

STI, , , , ActiveRecord ( Rails 3 ORM). AR, w.r.t. :

  • . . , , - , User . .
  • . , , , . , Ruby - . "", , . "" . , ORM . Martin Fowler .

, , , . . :

user = Client.new
# Do something to user
user.save
#=> <Client id: 1, name: "Michael Bolton", email: "mike@bolton.net", created_at: "2010-05-30 03:27:39", updated_at: "2010-05-30 03:27:39">

Rails 3 ActiveRecords.

+3

Source: https://habr.com/ru/post/1747243/


All Articles