如何在Rails中过滤与分组选择的关联

时间:2014-12-15 13:50:14

标签: 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 %>

给了我一组用户(活动和非活动)的分组选择。

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

为我提供了一些活跃用户。

我无法弄清楚将两者结合起来的语法。谢谢!

3 个答案:

答案 0 :(得分:0)

将按team_id

对所有活跃用户进行分组
scope :active_grouped, -> {where(active: true).group(:team_id)}

然后在您的视图中使用它

答案 1 :(得分:0)

您必须将ID添加到组子句中,例如:group("id, otherfield")

答案 2 :(得分:0)

我在user.rb中添加了一个方法:

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

并在我的表单中使用了grouped_option_for_select:

<%= f.select :user_id, grouped_options_for_select(User.for_select) %>

此博文非常有用:http://andrewradev.com/2011/05/25/grouped-select-helper-methods-in-rails/

任何人都有更好的方法吗?