【发布时间】:2012-09-12 12:57:02
【问题描述】:
像这样设置我的数据库(“类型”始终是用户,尽管我通过 STI 有不同类型的用户):
class User
# fields
# :id
# :sender_id, :sender_type
# :recipient_id, :recipient_type
end
明信片模型:
class Postcard < ActiveRecord::Base
belongs_to :owner, :class_name => User
belongs_to :recipient, :class_name => User
end
我想设置这样的用户模型:
class User < ActiveRecord::Base
has_many :postcards, :as => [:sender or :recipient] # this is not working
end
所以我可以说:
user.postcards
有可能吗?
PS:这条路我也试过了:
has_many :postcards, :finder_sql => Proc.new { "SELECT * FROM postcards WHERE postcards.owner_id=#{id} OR postcards.recipient_id=#{id}" }
但发现自己被困在范围内,因为 :finder_sql 重新创建了一个全新的 SQL:
User.postcards.by_status('new').size
【问题讨论】:
-
Rails 多态关联通常与您所写的不同。要做你的发送者或接收者,你通常会创建一个适用于两者的类,例如: class Postcard true end class Sender :mailable end class Receiver :mailable end
-
@joelparkerhenderson 感谢您的回复。不幸的是,我有多种用户类型,例如:Doctor
-
取决于您的设置方式。一般来说,Rails STI(单表继承)适用于具有大重叠恕我直言的类;设置类的更高级方法是从继承更改为关联(因此 Doctor has_one 用户)或更改为 DCI(数据上下文集成),这使医生和患者成为用户可以在运行时混合的两个“角色”。还有一种方法可以进行双面多态连接 - 尝试搜索 Evan Weaver 的旧 gem,看看它是否得到维护或有后继者。
标签: ruby-on-rails activerecord associations has-many-polymorphs