我的数据库设置是这样的("类型"总是User,尽管我通过STI有不同类型的User):
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
有可能吗?
附言:我也试过这条路:
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
正如joelparkerhenderson所提到的,我需要以不同的方式思考我的关联策略。
正如我想要的:
user.postcards
我的答案是简单地在明信片模型中使用范围:
scope :of_user, lambda { |user| where("recipient_id = ? OR owner_id = ?", user.id, user.id) }
所以我可以调用:
Postcard.of_user user
我甚至可以把它包装在用户模型中:
def postcards
Postcard.of_user self
end