像这样设置我的数据库(“类型”始终是用户,尽管我通过 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