0

我是学习 Ruby on Rails 和其他一切的新手。我想知道 Rails 是否有一种神奇的方法来实现这一点:

表格1

User table:
id, user_name, fake_id, user_fake_name

表 2

Post table:
id, fake_or_real, auth_id

fake_or_real 是一个布尔值;auth_id 是 user_id 或 user_fake_id 的外键。

如果 fake_or_real == 1,那么 auth_id = user_fake_id; auth_name = user_fake_name

如果 fake_or_real == 0,那么 auth_id = user_id; auth_name = 用户名

我使用两个 id 的原因是因为当用户在帖子中使用假名时,我想在 html 代码中隐藏 user_id。如果没有必要,请告诉我。

我应该怎么做才能获得可连接的作品,并使 post.auth_name 在这两种情况下都有效?

谢谢。

4

1 回答 1

1

To my knowledge there's no way to have foreign-key on one of to fields (and it's db limitation*). What you can do is

Let a User have a single FakeUser which delegates most of the attributes to User (except for id and name) A Post should then have a polimorphic association, let's call it authorable on other side of which may be a User or FakeUser. Voila!

More on polymorphic associations http://guides.rubyonrails.org/association_basics.html#polymorphic-associations

*limitation is not a good word here, it would be impossible to implement.

于 2013-07-01T07:31:42.370 回答