1

In the models of my app I want to have the option that the owner of each record is a user or a company...

Normally I have a user_id field (user model) in each model for keeping the owner...

What are the implementation options for this?

How can I design this?

Should I add another field in the models? owner? how can I use the user_id (user_model) or the company_id (company model)?

The data in the app could be:

  • Personal data of the specific user
  • Company data, which are separated from Personal data. Ofcourse company data also created by a certain user which is a member (with certain role) of the company...

Any ideas?

Thank you

  • This is a very interesting question, but it seems you can get better answers in the https://dba.stackexchange.com/ and/or https://softwareengineering.stackexchange.com/ StackExchange sites. – Sebastián Palma Apr 27 '20 at 08:35
  • You are correct... maybe the softwareengineering is better... do you know if I can move my question to this one? Thank you very much for your time :) – aAon - Andreas P. Gortsilas Apr 28 '20 at 16:43
  • You're welcome ;) I don't know if you can move it without mod intervention, but anyway you can just create them there as new questions. – Sebastián Palma Apr 28 '20 at 16:48

1 Answers1

0

this can be done with polymorphic associations, you have a model that can belongs to more than 1 model with the same relationship, see this example

class Picture < ApplicationRecord
  belongs_to :imageable, polymorphic: true
end

class Employee < ApplicationRecord
  has_many :pictures, as: :imageable
end

class Product < ApplicationRecord
  has_many :pictures, as: :imageable
end

for this to work you need to create an imageable_id and imageable_type on your picture table, fir this example.

you can check more information about this on rails documentation

xploshioOn
  • 4,035
  • 2
  • 28
  • 37
  • First I want to thank you for your reply... Second, in my case, it is not very clear what do you sugest for the model Product: class Picture < ApplicationRecord belongs_to :ownable, polymorphic: true end class User < ApplicationRecord has_many :products, as: :ownable end class Group < ApplicationRecord has_many :products, as: :ownable end and for another model, Customer? How it will be? "ownable again? or "productable", "customerable", and so on... In general I want to capture the owner info of each record in a lot of models... – aAon - Andreas P. Gortsilas Apr 27 '20 at 11:52