Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Optional or Conditional model associations in Rails

I have a user model. Users can have 1 of 3 roles: role1, role2, role3. This is represented by a 'role' column in the user model. Each role has a unique profile. role1_profile, role2_profile, role3_profile. Each *_profile is a model.

How do I represent this optional association in Rails?

I've tried it two different ways:

class User < ActiveRecord::Base
    #FIRST WAY
    if current_user.role == 'role1' then has_one :role1_profile end 
    #SECOND WAY
    has_one :role1_profile, :conditions => ['user.role = ?', 'role1']
end

But that doesn't work. What is the right way to do this?

like image 323
hrdwdmrbl Avatar asked Oct 11 '11 22:10

hrdwdmrbl


1 Answers

Associations are not intended to be conditional. It's probably easiest to keep things that way, too.

How about having a polymorphic association between User and the various role profiles?

class User
  belongs_to :role_profile, :polymorphic => true
end

class RoleXProfile
  has_many :users, :as => :role_profile
end

Of course, you would need to add the role_profile_id and role_profile_type fields to your users table.

No matter what you do you will need to check the user's role or role_profile wherever you use it.

like image 150
Wizard of Ogz Avatar answered Sep 30 '22 12:09

Wizard of Ogz