Conditional Relationships

1

I need your help

I have the following template:

class User < Ac...

   enum user_type: [:normal, :admin]
end

I also have the "Department" template:

class Department < A....

end

What I need is to do the type relationship:

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

How can I specify this type of relationship?

    
asked by anonymous 08.04.2015 / 12:11

3 answers

0

You will declare normally, it will only make it optional.

At any time, you can check if the association exists:

u = User.new
u.department.nil?
=> true
u.department_id = Department.first
u.department.nil?
=> false
    
08.04.2015 / 14:41
0

In the case of Department it's simple:

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

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

    
08.04.2015 / 22:56
0

You can not detonate the user_type field, and distinguish between normal users and admins by the presence of at least one department in their registry? Your problem seems to be that you're storing information about who's admin twice:

  • in field user_type
  • in relationship with Departmento
  • Do not Repeat Yourself! If only admins belong to a department, use this information to distinguish common users and admins (to keep compatibility with the code you already wrote, you can user_type be a computed property (I have no idea how this is done in Ruby, ideal was to have a view in the database, so other applications could also access this property without having to reimplement this logic ).

        
    16.06.2015 / 14:01