【问题标题】:"Complex" ActiveRecord association“复杂”ActiveRecord 关联
【发布时间】:2013-09-15 14:10:47
【问题描述】:

在设置一些 Active Record 关系时遇到了一些问题。

Users Leagues

Users 有很多PrimaryLeagues Users有很多SecondaryLeagues

我希望能够编写@user.primary_leagues 并获得已设置为主要的Leagues 列表。和@user.secondary_leagues 并获取已设置为辅助的Leagues 列表。

目前这里是我的课程的设置方式,但不知何故它是错误的......

class User < ActiveRecord::Base

has_many :primary_leagues, class_name: 'PrimaryLeague', foreign_key: 'league_id'

has_many :secondary_leagues, class_name: 'SecondaryLeague', foreign_key: 'league_id'

...

class PrimaryLeague < ActiveRecord::Base

belongs_to :user
belongs_to :league

...

class League < ActiveRecord::Base

has_many :primary_users, class_name: 'PrimaryLeague', foreign_key: 'user_id'
has_many :secondary_users, class_name: 'SecondaryLeague', foreign_key: 'user_id'

有什么想法吗?

【问题讨论】:

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


    【解决方案1】:

    据我了解,您只想对整个事情使用两个类(这是有道理的)。所以:

    class User < ActiveRecord::Base
      has_many        :primary_league_ownerships
      has_many        :primary_leagues,
                      :through => :primary_league_ownerships,
                      :source => :league
      has_many        :secondary_league_ownerships
      has_many        :secondary_leagues,
                      :through => :secondary_league_ownerships,
                      :source => :league
    end
    
    class PrimaryLeagueOwnership < ActiveRecord::Base
      belongs_to      :user
      belongs_to      :league
    end
    
    class SecondaryLeagueOwnership < ActiveRecord::Base
      belongs_to      :user
      belongs_to      :league
    end
    
    class League < ActiveRecord::Base
      has_many        :primary_league_ownerships
      has_many        :primary_users,
                      :through => :primary_league_ownerships,
                      :source => :user
      has_many        :secondary_league_ownerships
      has_many        :secondary_users,
                      :through => :secondary_league_ownerships,
                      :source => :user
    end
    

    请记住,:class_name 应该是保存目标关联的实际类。

    【讨论】:

    • 德帕谢谢!联赛可以有很多primary_users ...我也想能够说@league.primary_users ...我想也许我需要一个has many through association?
    • assert_valid_keys':未知键:association_foreign_key (ArgumentError) .... 应该是 has_and_belongs_to_many 关联吗?
    • 你是对的,我犯了一个错误。它可能应该是:foreign_key 而不是:association_foreign_key。如果您查看has_many 协会接受的选项,:association_foreign_key 根本不是其中之一。 guides.rubyonrails.org/…
    • 谢谢德帕。我想通了,并在我的代码中进行了更新。可能想要更新答案以防其他人看到。很大的帮助...现在运行我的测试...看看这一切是否有效!
    • 在模型 PrimaryLeagueOwnership 中找不到源关联:primary_league 或 :primary_leagues。试试 'has_many :primary_leagues, :through => :primary_league_ownerships, :source => '。是 :user 还是 :league 之一?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多