Ruby on rails 如何在Rails中筛选与分组选择的关联

Ruby on rails 如何在Rails中筛选与分组选择的关联,ruby-on-rails,associations,simple-form,Ruby On Rails,Associations,Simple Form,我还可以确定我的用户范围: Team has_many :users User belongs_to :team 在我的表单中,我希望选择按团队分组的活动用户 scope :active, -> (active) {where active: active } <%= f.association :user, collection: Team.all, as: :grouped_select, group_method: :users %> 提供按团队分组选择的用户(

我还可以确定我的用户范围:

Team has_many :users
User belongs_to :team
在我的表单中,我希望选择按团队分组的活动用户

scope :active, -> (active) {where active: active }
<%= f.association :user, collection: Team.all, as: :grouped_select, group_method: :users %>

提供按团队分组选择的用户(活动和非活动)

scope :active, -> (active) {where active: active }
<%= f.association :user, collection: Team.all, as: :grouped_select, group_method: :users %>

给我一个活动用户的选择


我想不出将两者结合起来的语法。谢谢

将按
团队id对所有活动用户进行分组

<%= f.association :user, collection: User.where(active: true) %>

然后在视图中使用它

您必须将id添加到group子句中,如:
group(“id,otherfield”)
我在我的user.rb中添加了一个方法:

scope :active_grouped, -> {where(active: true).group(:team_id)}
并在我的表格中为选择使用分组的选项:

def self.for_select
  Team.active.map do |team|
    [team.name, team.users.active(true).map { |u| [u.name, u.id] } ]
  end
end

这篇博文很有帮助:

有人有更好的方法吗?

我在视图中尝试过,但出现了一个错误PG::GroupingError:error:groupby子句中必须出现“users.id”列