【问题标题】:Is it possible to assign multiple has_many ":as" polymorphic relation on same field?是否可以在同一字段上分配多个 has_many ":as" 多态关系?
【发布时间】: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


【解决方案1】:

正如 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-04-06
    • 2011-05-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多