带连接表的范围关联元素

时间:2017-11-17 14:37:01

标签: ruby-on-rails ruby scope activemodel

我正在尝试范围我的用户的主要组。这个组用猫注意:它是2。

所以我想用

这样的范围来做这件事
class User < ApplicationRecord
  has_many :users_group, dependent: :destroy
  has_many :groups, through: :users_group

  scope :my_group, -> { self.joins(:groups).where('groups.cat = 2').limit(1) } 
end

但是下面的命令不起作用:

  

current_user.my_group

你能指导我实现它的好方法吗?

2 个答案:

答案 0 :(得分:2)

current_user没有返回ActiveRecord关系,它只是返回用户,因此您无法将其与范围链接在一起(我假设您错误消息是&#39;得到的是undefined method 'my_group' for #<User>?)。将范围添加到类,并通过groups has_many关系使用它,例如 current_user.groups.my_group

答案 1 :(得分:2)

正如马里奥所说,范围适用于集合,而非实例。

如果您想将方法保留在User模型中,可以使用以下内容:

<强> user.rb

def my_group
  groups.find_by_cat(2)
end

使用find_by将返回单个群组,而不是使用where / limit。如果找不到该论坛,则会返回nil

我建议使用范围返回单个实例是一种反模式,使用此方法或将以下方法放入Group并调用{ {1}} - 虽然名称current_user.groups.my_group听起来有点不合适。为了完整起见,这里无论如何:

<强> group.rb

my_group