【发布时间】:2010-09-23 17:10:49
【问题描述】:
我有四个模型,示例如下:
用户有一个 A、B 或 C。
User.user_type = "A"
User.user_type_id = 12
结合起来,user_type 和 user_type_id 标识了特定用户所绑定的表和记录(在本例中,我们的用户连接到表 A 中的记录 #12)。
在用户/新表单上,用户决定他们是什么用户类型,并且表单将包含“A”、“B”或“C”的 params[:user_type] 传递给用户控制器/:create。
基于传递给 Users/create 的 params[:user_type],我需要构建一个新的 A、B 或 C。这是我目前所拥有的:
Users controller, create:
if @user.save # user_type is present, user_type_id is not
if @user.user_type == "A"
@a = A.new.save(false) # build a new A and bypass validation
@user.user_type_id = @a.id # set user's user_type_id.
@user.save(false) # minor update so save without validation
elsif @user.user_type == "B"
...
elsif @user.user_type == "C"
...
end
end
此代码每次都错误地给我“2”作为 user_type_id。我知道我通常会以错误的方式进行此操作,但我不知道如何最简洁地做到这一点。有什么建议吗?
-----编辑------
我确实设置了多态关联。我目前的设置是:
用户属于_to :authenticable, :polymorphic => true
A has_many :users, :as => :authenticable(B 和 C 类似)
【问题讨论】:
-
您写了用户 has_many As、Bs 和 Cs。但从您的代码来看,用户似乎只能拥有一个 A、B 或 C。我也建议使用多态关联。
-
彼得,你是对的 - 一个用户只能拥有一个 A、B 或 C。
-
那么对于给定的 A 实例,它是否只有一个用户?或者它可能有许多不同的用户?在你的情况下,我猜只有一个,对吗?
-
彼得,没错。 A、B 和 C 是包含不同类型信息的表格,具体取决于人员是谁。然而,每个人都是用户,都有用户名、密码等。