【问题标题】:Rails has_many through - query through the relationshipRails has_many through——通过关系查询
【发布时间】:2020-08-17 20:08:08
【问题描述】:

运行 rails 6.0.3.2 / ruby​​ 2.7.1

我有一个不符合预期的 has_many through-relationship。

我的模型如下所示:

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

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

【问题讨论】:

    标签: ruby-on-rails activerecord


    【解决方案1】:

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

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

    更多信息here。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-20
      • 1970-01-01
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多