2013-10-16 17 views
2

我有一個選擇列表,我想用一些硬編碼值以及來自AR的一些值來填充。例如,我有一個供用戶選擇交易付款選項的列表。將硬編碼值與選擇列表中模型的值結合起來

  • 信用卡
  • 現金
  • 禮券

很容易的......

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

現在我想刪除通用的 「信用卡」 選項,並加入每用戶已存檔的信用卡(例如,每個PaymentMethod型號屬於User

  • 你萬事達卡在1234結束
  • 你美國運通在4321結束
  • 現金
  • 禮券

我知道如何獨自做兩個,但我似乎無法弄清楚如何融合它們。請注意,我正在使用select_tag而不是FormHelper.select,因爲這不一定對應於模型上的屬性。

+0

如何創建一個數組,然後傳遞一個數組中options_for_select? –

回答

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") %> 
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。我在猜測一些變量名稱,因爲你沒有發佈相關的代碼。