将硬编码值与选择列表中的模型中的值组合在一起

时间:2013-10-16 16:45:11

标签: ruby-on-rails activerecord ruby-on-rails-4

我有一个选择列表,我想用一些硬编码值和AR中的一些值填充。例如,我有一个列表供用户选择交易的付款选项。

  • 信用卡
  • 现金
  • 礼券

够容易......

<%= select_tag :paying_with, options_for_select([["Credit card", "credit_card"], ["Cash", "cash"], ["Gift Certificate", "gift_certificate"]] %>

现在,我想删除通用的“信用卡”选项,并包含用户存档的每张信用卡(例如属于PaymentMethod的每个User模型)

  • 您的万事达卡以1234结尾
  • 您的AmEx以4321结尾
  • 现金
  • 礼券

我知道如何单独进行,但我似乎无法弄清楚如何混合它们。请注意,我使用的是select_tag而不是FormHelper.select,因为这不一定与模型上的属性相对应。

2 个答案:

答案 0 :(得分:1)

@options = @user.credit_cards.map{ |c| ["Your #{c.card_name} ending in #{c.card_last_four_digits", c]}.insert(["Cash", "cash"]).insert(["Gift Certificate", "gift_certificate"])

这将为您提供一个传递给options_for_select的数组。我猜测一些变量名称,因为你没有发布相关的代码。

答案 1 :(得分:0)

我最终结合了Nikita的评论和优秀的旧时尚<<运营商。我原本想在视图中保留查询,但那里的查询过于复杂。

    @payment_options = []
    @payment_options << ["No charge", "no_charge"]
    @payment_options += PaymentMethod.where(...).map { |p| [p.name, p.id] }.to_a
    @payment_options << ["Cash", "cash"]
    @payment_options << ["Gift Certificate", "gift_certificate"]

......并且在视图中......

<%= select_tag :paying_with, options_for_select(@payment_options, enrollment.paying_with || "no_charge") %>
相关问题