【问题标题】:has_one/has_many with dependent destroy but using a different name for the keyhas_one/has_many 具有依赖销毁但使用不同的键名
【发布时间】:2013-04-03 02:49:43
【问题描述】:

所以我正在查看某人的代码,其中包含以下内容(意译):

class user
  has_one :connection, :dependent => :destroy
  has_one :second_user, :through => :connection, :class_name => 'User'
end

class connection
  belongs_to :user
  belongs_to :second_user, :class => 'User'
end

如果我有一个连接对象并删除关联的“用户”,它可以被很好地销毁。但我也想这样做,如果占用“second_user”字段的用户被破坏,则连接被破坏。我怎样才能在不搞太多麻烦的情况下无缝地完成这一点(希望不需要迁移)?

谢谢!

【问题讨论】:

    标签: ruby-on-rails model associations polymorphic-associations dependent-destroy


    【解决方案1】:

    请注意,单个用户可以与两个连接相关联。这意味着在用户(作为第二个用户)和尚未定义的连接之间存在另一个关联。我就叫它secondary_connection

    class User
      has_one :connection, :dependent => :destroy
      has_one :secondary_connection, :class_name => 'Connection', :foreign_key => :second_user_id, :dependent => :destroy  # Inverse of Connection second_user
      has_one :second_user, :through => :connection, :class_name => 'User'
    end
    

    【讨论】:

    • +1 虽然我可能会调用该协会:secondary_connection
    • 感谢 PinnyM 的建议,使用了更好的关联名称。我会处理我的命名选择。
    猜你喜欢
    • 1970-01-01
    • 2010-11-26
    • 2015-06-01
    • 2017-01-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-04-26
    • 1970-01-01
    相关资源
    最近更新 更多