Rails has_many through - 通过关系查询

Rails has_many through - query through the relationship

运行 rails 6.0.3.2 / ruby 2.7.1

我有一个 has_many 直通关系,但没有按预期表现。

我的模型是这样的:

class Item < ApplicationRecord
       has_many :item_permissions
       has_many :users, :through => :item_permissions
end

class User < ApplicationRecord
      has_many :item_permissions
      has_many :items, :through => :item_permissions
end

class ItemPermission < ApplicationRecord
    belongs_to :items
    belongs_to :users
end

现在我想检索某个用户有权访问的所有项目:

u = User.find(1)

u.items

给我一个错误:

NameError (uninitialized constant User::Items)

我可以通过

获得权限条目
u.item_permissions

有没有办法为某个用户检索项目,或者反过来接收链接到特定项目的所有用户?

错误出在您的 belongs_to 声明中,您都使用复数词而不是单数词来引用相关模型。尝试:

class ItemPermission < ApplicationRecord
    belongs_to :item # :item instead of :items
    belongs_to :user # :user instead of :users
end

更多信息here