【问题标题】:how to filter association with grouped select in Rails如何在 Rails 中过滤与分组选择的关联
【发布时间】:2014-12-15 13:50:13
【问题描述】:
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) %>

给我选择的活跃用户。

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

【问题讨论】:

    标签: ruby-on-rails associations simple-form


    【解决方案1】:

    我在 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/

    谁有更好的方法?

    【讨论】:

      【解决方案2】:

      将所有活跃用户按team_id分组

      scope :active_grouped, -> {where(active: true).group(:team_id)}
      

      然后在你的视图中使用它

      【讨论】:

      • 我在我的视图中尝试过 但收到错误 PG::GroupingError: ERROR: column "users.id" must appear in the GROUP BY 子句
      【解决方案3】:

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2013-06-27
        • 1970-01-01
        • 1970-01-01
        • 2012-01-15
        • 2015-07-10
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多