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 the role column in the user model. Each role has a unique profile. role1_profile, role2_profile, role3_profile. Each * _profile is a model.

How to represent this optional association in Rails?

I tried this in 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 does not work. What is the right way to do this?

+5
source share
2 answers

Associations should not be conditional. It's probably easiest to keep things the same.

User ?

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

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

, role_profile_id role_profile_type .

, , role_profile , .

+4

.

, :conditions - , ( ).

, , , , , , .

+4

All Articles