Belongs_to 基于字段的值
我有一个包含条目的表,每个条目可以有不同的帐户类型。我试图根据 cindof
的值定义并返回帐户。
每种帐户类型都有一个表,account_site
和 account_page
。所以常规的 belongs_to
是不行的。
那么有没有什么方法可以返回类似的内容:
belongs_to :account, :class_name => "AccountSite", :foreign_key => "account_id" if cindof = 1
belongs_to :account, :class_name => "AccountPage", :foreign_key => "account_id" if cindof = 2
也尝试过在方法中做到这一点,但没有运气。确实希望只有一个帐户
,而不是不同的belongs_to
名称。 谁能明白我想要什么?很难用英语解释。
特尔夫
I have a table with entries, and each entries can have different account-types. I'm trying to define and return the account based on the value of cindof
Each account type has one table, account_site
and account_page
. So a regular belongs_to
won't do.
So is there any way to return something like:
belongs_to :account, :class_name => "AccountSite", :foreign_key => "account_id" if cindof = 1
belongs_to :account, :class_name => "AccountPage", :foreign_key => "account_id" if cindof = 2
Have tried to do that in a method allso, but no luck. Really want to have just one account
and not different belongs_to
names.
Anyone that can figure out what I want? Hard to explain in English.
Terw
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您应该能够通过多态关联做您想做的事情。默认情况下,这不会打开
cindof
,但这可能不是问题。您将需要
account_id
列和account_type
列。然后,帐户对象的类型存储在额外类型列中。这将让你做:
或者
You should be able to do what you want with a polymorphic association. This won't switch on
cindof
by default, but that may not be a problem.You will need both an
account_id
column and aaccount_type
column. The type of the account object is then stored in the extra type column.This will let you do:
or
我会研究单表继承。不是 100% 确定,但我认为它可以解决您的问题 http ://code.alexreisner.com/articles/single-table-inheritance-in-rails.html
如果这不好,那么您自己实现并不难。
I would look into Single Table Inheritance. Not 100% sure, but I think it would solve your problem http://code.alexreisner.com/articles/single-table-inheritance-in-rails.html
If that isn't good, this isn't too hard to implement yourself.