2017-08-24 111 views
0

我正在寻找一个地理缓存应用程序,用户可以在其中创建新缓存或访问现有缓存。下面是型号:与连接表和多个别名的多对多关联

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: Could not find the source association(s) :caches in model Usercache. Try 'has_many :visited_caches, :through => :usercaches, :source => '. Is it one of user or cache?

当我重新安排的建议的关联,但是,错误是一样的。是否有一些我想念的小细节,还是我正在为完成我想要的完全不正确的范式工作?

回答

1

source必须以单数形式来提供(所述documentation用于has_many提供了一种例如用于它):

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