Rails中的可选或条件模型关联

hrd*_*rbl 5 activerecord ruby-on-rails associations has-one belongs-to

我有一个用户模型.用户可以拥有3个角色中的1个:role1,role2,role3.这由用户模型中的"角色"列表示.每个角色都有独特的个人资料.role1_profile,role2_profile,role3_profile.每个*_profile都是一个模型.

如何在Rails中表示此可选关联?

我尝试过两种不同的方式:

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
Run Code Online (Sandbox Code Playgroud)

但这不起作用.这样做的正确方法是什么?

Wiz*_*Ogz 4

关联并不是有条件的。保持这种状态可能也是最容易的。

User在各种角色配置文件之间建立多态关联怎么样?

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

class RoleXProfile
  has_many :users, :as => :role_profile
end
Run Code Online (Sandbox Code Playgroud)

当然,您需要将role_profile_idrole_profile_type字段添加到您的用户表中。

无论您做什么,无论您在何处使用,都需要检查用户的角色或 role_profile。