2013-09-26 46 views
1

我實際上在我的Rails項目中使用了表單助手radio_button。如果一切正常,代碼本身不會對我來說很好:Rails radio_button重構最佳實踐

_form.html.haml

#- Loop on durations types 
- Product::DURATIONS.each_with_index do |name, index| 
    #- If new record, then select the first index by default 
    - unless @product.duration_type.present? 
    - checked = (index == 0) ? true : false 
    - else 
    #- Otherwise, if edit, then select the product value 
    - checked = (name == @product.duration_type) ? true : false 
    = f.radio_button :duration_type, name, checked: checked 
    = f.label :duration_type, name 

product.rb

DURATIONS = %w(Hour Day Week Month Year) 

有沒有更好的辦法以更乾和Rails的方式寫這篇文章?

非常感謝

回答

1

不知道這是鐵的方式,但它是一個有趣的方式,節省了一些行。

這個想法是將對象的持續時間的索引與循環中的當前索引進行比較。如果@product.duration_type不在Product::DURATIONS或零,則返回nil,其由to_i轉換爲整數給出0或第一個單選按鈕。

#- Loop on durations types 
- Product::DURATIONS.each_with_index do |name, index| 
    - checked = Product::DURATIONS.index(@product.duration_type).to_i == index 
    = f.radio_button :duration_type, name, checked: checked 
    = f.label :duration_type, name 

其他選項更具可讀性。

#- Loop on durations types 
- Product::DURATIONS.each_with_index do |name, index| 
    - checked = @product.duration_type ? (name == @product.duration_type) : (index == 0) 
    = f.radio_button :duration_type, name, checked: checked 
    = f.label :duration_type, name 
+0

真棒哥們,謝謝:) – lkartono

+0

,因爲在它的一個錯誤改變了第二種方法。 – tihom