我有一个用户模型。
用户可以拥有以下 3 个角色之一: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
但这不起作用。这样做的正确方法是什么?
最佳答案
关联不是有条件的。保持这种状态可能也是最容易的。
在 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。
关于ruby-on-rails - Rails 中的可选或条件模型关联,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7733341/