Conditional relationships

Asked

Viewed 169 times

1

I need your help

I have following model:

class User < Ac...

   enum user_type: [:normal, :admin]
end

And I also have the model "Department":

class Department < A....

end

What I need to do is make the relationship like:

User belongs (belongs_to) to a Department, but only when the type is "admin"; And the Department should have (has_many) several users but only "admin type"

How can I specify this type of relationship?

3 answers

0

You can’t detonate the field user_type, and distinguish between normal users and admins by the presence of at least one department in his register? Your problem seems to be that you are storing information about who is admin twice:

  1. in the field user_type
  2. in the relationship with the Departmento

Don’t Repeat Yourself! If only admins belong to a department, use that one information to distinguish common users and admins (to maintain compatibility with the code you have already written, you can do user_type be a computed property (I have no idea how to do this in Ruby; ideal would be to have a view in the database, so other applications can also access this property without having to reimplement this logic).

0

You will declare normally, just make it optional.

When you want, you can check if the association exists:

u = User.new
u.department.nil?
=> true
u.department_id = Department.first
u.department.nil?
=> false

0

In the case of the Department it’s simple:

class Department < ActiveRecord::Base
  has_many :users , ->(u) { where(user_type:User.user_types[:admin]) }
end

In User’s case, Rails has no conditional relationship. An option would be to keep with belongs_to, and validate at the time of creation/update, only to let create when the user is of the admin type.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.