【问题标题】:Many-to-many association with join table and multiple aliases与连接表和多个别名的多对多关联
【发布时间】:2017-08-24 16:27:35
【问题描述】:

我正在开发一个地理缓存应用程序,用户可以在其中创建新的缓存或访问现有的缓存。以下是模型:

class User < ApplicationRecord
  has_many :usercaches
  has_many :visited_caches, source: :caches, through: :usercaches
  has_many :created_caches, class_name: :caches
end

class Cache < ApplicationRecord
  has_many :usercaches
  has_many :visitors, source: :users, through: :usercaches
end

class Usercache < ApplicationRecord
  belongs_to :user 
  belongs_to :cache 
end

连接表看起来是这样,因为我一直在尝试消除与大写或复数相关的任何潜在错误。每当我在 Rails 控制台中创建用户并尝试查看 new_user.visited_caches 时,都会收到以下错误:

ActiveRecord::HasManyThroughSourceAssociationNotFoundError: 不能 找到源关联:模型 Usercache 中的缓存。尝试 'has_many :visited_caches, :through => :usercaches, :source => '。是用户还是缓存之一?

但是,当我按照建议重新排列关联时,错误仍然相同。是否有一些我遗漏的小细节,或者我正在使用一个完全不正确的范例来完成我想要完成的事情?

【问题讨论】:

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


    【解决方案1】:

    source 必须以单数形式提供(has_manydocumentation 提供了一个示例):

    class User < ApplicationRecord
      has_many :usercaches
      has_many :visited_caches, source: :cache, through: :usercaches
      has_many :created_caches, class_name: :caches
    end
    
    class Cache < ApplicationRecord
      has_many :usercaches
      has_many :visitors, source: :user, through: :usercaches
    end
    
    class Usercache < ApplicationRecord
        belongs_to :user 
        belongs_to :cache 
    end
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 1970-01-01
      • 2014-12-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多