【问题标题】:Has many :through, a better way to do this?有很多:通过,更好的方法来做到这一点?
【发布时间】:2012-08-25 13:12:38
【问题描述】:

我已经建立了一个类似于 facebook 的线程消息系统,其中一个用户可以同时进行许多对话。这些对话中的每一个都涉及一组独特的人,并且每个对话都包含多条消息。

class User < ActiveRecord::Base
  has_many :involvements
  has_many :conversations, through: :involvements, unique: true
end

class Involvement < ActiveRecord::Base
  belongs_to :user
  belongs_to :involvable, polymorphic: true
end

class Conversation < ActiveRecord::Base
  has_many :involvements, as: :involvable
  has_many :participants, through: :involved, class_name: "User", unique: true
  has_many :messages
end

class Message < ActiveRecord::Base
  belongs_to :conversation
end

我得到了它,但我不禁觉得必须有一些更好、更有效的方法来压缩这个设置,例如使用 3 个模型。或者可能使用具有独特列或其他东西的 habtm...

四个发送消息的模型似乎太多了。有什么建议么?或者这是我不应该担心的事情?

【问题讨论】:

  • 为什么 4 看起来太多了?有 4 条数据参与其中:用户、他们对对话的参与、对话以及这些对话中的消息。您的设置看起来非常合理。

标签: ruby-on-rails associations has-many-through


【解决方案1】:

看看has_and_belongs_to_many,这可能是您摆脱其中一个模型的一种方式。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多