【问题标题】:Rails - multiple associations to same modelRails - 同一模型的多个关联
【发布时间】:2012-03-19 21:48:57
【问题描述】:

我正在构建一个 Rails 应用程序来跟踪一个群体(假设是一个家庭)成员之间的费用/债务。到目前为止,我有组、用户和费用的模型 - 基础知识。现在我正在尝试找出组和用户之间的关联。例如,一个组可以有很多用户,一个用户可以拥有/属于很多组,所以我使用连接表设置了一个 HABTM 关联。但我很困惑,因为一个组也可以有一个所有者,它也是一个用户。这就是我现在的位置:

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
    has_one :owner, :class_name => "User"
end

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
end

Group 表上当前有一个 owner_id 字段,但是当我尝试执行任何涉及 group.owner 的操作时,我收到了一个 PostgreSQL 错误 column users.group_id does not exist。我很迷茫 - 关于在这里表示多个关联到同一模型的最佳方式的任何想法?

【问题讨论】:

  • HABTM 已经表示该组有很多用户,对吧?因此,其中一位用户也必须是“所有者”。您可以做的是使用has_many :through 并使用其中的一个字段来指定组的所有者。

标签: ruby-on-rails activerecord polymorphic-associations


【解决方案1】:

所以我想我遵循你想要得到的,这是在 Dia 中创建的快速 ERD:

看起来您只需要添加用户和组之间所有权的直接关联。我使用了owner_id 列,因此表和模型更加清晰,避免了多个 user_id 列的混淆。那么以下模型将起作用:

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users
    belongs_to :owner, :class_name => "User", :foreign_key => "owner_id"
end

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups
    has_many :owned, :class_name => "Group", :foreign_key => "owner_id"
end

【讨论】:

  • 我没有注意到我的代码中User 的双重属性groups,加上你。
  • 成功!看起来我在我的 Group 模型中切换了 has_one-/belongs_to- 所有者关联,并且 :owned 解决方案是完美的。也喜欢图表。谢谢!
【解决方案2】:

怎么样:

class Group < ActiveRecord::Base
    has_and_belongs_to_many :users, :through => :membership
    has_one :owner, :class_name => "User"
end

class User < ActiveRecord::Base
    has_and_belongs_to_many :groups, :through => :membership
    has_many :owned, :class_name => "Group"
end

并使用user_idgroup_id 创建模型Membership

【讨论】:

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