I'm working on a geocaching application where users can create a new cache or visit an existing one. Here are the models:
我正在开发一个地理缓存应用程序,用户可以在其中创建新缓存或访问现有缓存。以下是模型:
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
The join table looks the way it does because I've been trying to eliminate any potential errors related to capitalization or pluralization. Whenever I create a User in Rails console and try to look at new_user.visited_caches
, I get the following error:
连接表看起来像它的方式,因为我一直在努力消除任何与大写或复数相关的潜在错误。每当我在Rails控制台中创建User并尝试查看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?
ActiveRecord :: HasManyThroughSourceAssociationNotFoundError:找不到源关联:模型Usercache中的缓存。尝试'has_many:visited_caches,:through =>:usercaches,:source =>'。它是用户还是缓存之一?
When I rearrange the association as suggested, however, the error remains the same. Is there some small detail I'm missing, or am I working with a completely incorrect paradigm for what I want to accomplish?
但是,当我按照建议重新排列关联时,错误保持不变。是否有一些我遗漏的小细节,或者我正在使用一个完全不正确的范例来完成我想要完成的工作?
1 个解决方案
#1
1
source
must be provided in a singular form (the documentation for has_many
provides an example for it):
source必须以单数形式提供(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
#1
1
source
must be provided in a singular form (the documentation for has_many
provides an example for it):
source必须以单数形式提供(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