【问题标题】:Using model constants as groups in Rails grouped_collection_select在 Rails grouped_collection_select 中使用模型常量作为组
【发布时间】:2022-06-19 12:05:59
【问题描述】:

我正在构建一个表单,用户可以在其中创建金融交易。一个字段是银行帐户的下拉列表。

我希望此下拉列表按每个帐户的帐户类型(BankAccount::ACCOUNT_TYPE - 每个 BankAccount 记录中的属性)对所有列出的银行帐户进行分组。

如果我现在手动编写所有代码,代码将如下所示:

<%= f.select :bank_account_id,
    {
      'On-Budget' => ['Cash',
                     'Credit Card 1',
                     'Credit Card 2',
                     'Venmo'],
      'Off-Budget' => ['Investment Bank 1',
                     'Investment Bank 1'],
      'Closed' => ['Old Bank 1',
                     'Old Bank 2'],
    }   %>

app/models/bank_account.rb - 我在其中定义 ACCOUNT_TYPES

class BankAccount < ApplicationRecord
ACCOUNT_TYPES = %w(On-Budget Off-Budget Closed).freeze
...
end

这是我的工作 collection.select,没有分组

<%= f.collection_select :bank_account_id, 
                        BankAccount.all, 
                        :id, 
                        :name, 
                        {prompt: 'Select an account'} %>

从 rails API,我认为 grouped_collection_select 是我需要的 (https://api.rubyonrails.org/classes/ActionView/Helpers/FormBuilder.html#method-i-grouped_collection_select)

grouped_collection_select(method, collection, group_method, group_label_method, option_key_method, option_value_method, options = {}, html_options = {})

使用BankAccount::ACCOUNT_TYPES 作为我的 group_method,而 group_label_method 不起作用。

<%= f.grouped_collection_select(:bank_account_id,
                                BankAccount.all,
                                BankAccount::ACCOUNT_TYPES, (group_method?)
                                BankAccount::ACCOUNT_TYPEs, (group_label_method?)
                                :id,
                                :name,
                                {prompt: 'Select an account' } %>

【问题讨论】:

标签: ruby-on-rails forms drop-down-menu


【解决方案1】:

我从这个 SO 问题中找到了答案:https://stackoverflow.com/questions/36854817/use-grouped-collection-select-to-group-a-model-by-enum

我创建了一个辅助方法

def grouped_bank_account_options_for_select(selected_bank_account_id = nil)
    options = {}
    BankAccount::ACCOUNT_TYPES.each do |t|
      unless t == "Closed"
        options[t] = BankAccount.where(account_type: t)
                                .pluck(:name, :id)
      end
    end
    grouped_options_for_select(options, selected_bank_account_id)
  end

然后在视图的表单助手中调用它

<%= select_tag :bank_account_id, grouped_bank_account_options_for_select(params[:bank_account_id]), {prompt: 'Select an account'} %>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-16
    • 1970-01-01
    • 2016-03-17
    • 2019-01-04
    相关资源
    最近更新 更多