【问题标题】:Self-referencing models in Rails 3Rails 3 中的自引用模型
【发布时间】:2011-01-18 18:01:19
【问题描述】:

我有一个实体模型,我想显示实体之间的连接。即,实体 1 连接到实体 2。

我现在的想法是在两者之间创建一个名为 Connection 的连接模型,并让它像传统的 Rails 连接表一样工作。除了列entity_one_id和entity_two_id之外,Entity和Connection之间建立多对多的关系。

这似乎是一种非常不优雅的方式。我想知道是否有人有更好的想法?也许是我没有看到的更类似于 rails 的东西?

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-3 models self-join


    【解决方案1】:

    这是最常见的方法。如果一个实体只连接到另一个模型,您可以使用链表、树状结构。

    查看Ryan Bates' Railscast on self-joining models。它处理类似于社交网络的系统,但它仍然具有您需要的原则并提供了一个很好的起点

    【讨论】:

      【解决方案2】:

      你可以使用这个实现:

      class User < ActiveRecord::Base
        has_many :friends, :through => :friendships, :conditions => "status = 'accepted'"
        has_many :requested_friends, :through => :friendships, :source => :friend, :conditions => "status = 'requested'", :order => :created_at
        has_many :pending_friends, :through => :friendships, :source => :friend, :conditions => "status = 'pending'", :order => :created_at
        has_many :friendships, :dependent => :destroy
      end
      
      
      class Friendship < ActiveRecord::Base
         belongs_to :user
         belongs_to :friend, :class_name => "User"
      end
      

      【讨论】:

      • 你从 Ryan 的 Railscast 偷来的实现? :)
      • 确实我不记得我在哪里捡到它了,但你绝对是对的 :)
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-07-03
      • 2021-02-19
      相关资源
      最近更新 更多