1

I have a model, called Procedure which has to be owned by a user and assigned to another user. I have a single table User, with roles to distinguish users.

So a procedure has 2 references to the table User.

I found and implemented this solution here so in my Procedure model I have

belongs_to :owner, class_name: "User", foreign_key: "owner_id"
belongs_to :assignee, class_name: "User", foreign_key: "assignee_id"

and in model User I have this

has_many :owned_procedures, class_name: "Procedure", foreign_key: "owner_id"
has_many :assigned_procedures, class_name: "Procedure", foreign_key: "assignee_id"

but I cannot understand how this physically should be implemented, I mean at table level: does table procedures need to have both the fields owner_id and assignee_id, or just a field user_id?

Pavan
  • 33,316
  • 7
  • 50
  • 76
sissy
  • 2,908
  • 2
  • 28
  • 54

1 Answers1

2

Does table procedures need to have both the fields owner_id and assignee_id, or just a field user_id

You should have both owner_id and assignee_id in procedures table instead of user_id so that you can call

@user.owned_procedures
@user.assigned_procedures

to get owned_procedures and assigned_procedures of a @user which is an instance of User. And to get a owner and assignee of a procedure, call

@procedure.owner
@procedure.assignee
Pavan
  • 33,316
  • 7
  • 50
  • 76
  • Ok, what still makes me wondering is that in this way there is no foreign_key constraint in the database that binds the two tables, after a migration. Shall I add it manually? Or shall I delegate only Rails to keep track of the association?Thank you very much, I will accept anyway your answer later. – sissy Sep 13 '18 at 14:36
  • @sissy With the associations, Rails will take care of it. You can confirm this by creating some procedure records in the console, map them to respected owner and assignee and call `@user.owned_procedures` or `@user.assigned_procedures`, check the SQL query that got performed. – Pavan Sep 13 '18 at 15:01
  • yea I'm proceeding with it. Thank you again :) – sissy Sep 13 '18 at 15:04