高度以英寸存儲在數據庫中。將多輸入虛擬屬性移動到SimpleForm自定義輸入組件
然而英尺和英寸需要自己單獨的輸入形式:
Height: [_______] feet [_______] inches
所以我用虛擬屬性,並得到了它的工作。這裏是我的模型的簡化版本:
class Client < ActiveRecord::Base
attr_accessible :name, :height_feet, :height_inches
before_save :combine_height
def height_feet
height.floor/12 if height
end
def height_feet=(feet)
@feet = feet
end
def height_inches
if height && height%12 != 0
height%12
end
end
def height_inches=(inches) #on save?
@inches = inches
end
def combine_height
self.height = @feet.to_d*12 + @inches.to_d #if @feet.present?
end
end
而且_form
部分使用simple_form:
<%= simple_form_for(@client) do |f| %>
<ul>
<%= f.error_notification %>
<%= f.input :name %>
<%= f.input :weight %>
<li>
<%= f.input :height_feet, :label => 'Height', :wrapper => false %>
<span>feet</span>
<%= f.input :height_inches, :label => false, :wrapper => false %>
<span>inches</span>
</li>
<%= f.error :base %>
</ul>
<%= f.button :submit %>
<% end %>
這工作。不過這是不理想的。
我想幹這個並創建一個custom input component,所以我可以使用<%= f.input :height, as: :feet_and_inch %>
將表格高度添加到表格中,因此可以使用其他任何類似<%= f.input :wingspan, as: :feet_and_inch %>
的圖案。
我已經對自定義組件進行了實驗,但是我無法獲得兩個輸入來顯示 - 而且我不確定哪裏是將轉換邏輯從英尺和英寸放到英寸的最佳位置(同樣也是如此從英寸到英尺和英寸)。
爲什麼不使用簡單的輔助方法?對於我來說,不需要添加自定義輸入組件......而且,接收表單構建器的輔助方法是執行所需內容的最簡單,最乾燥的方式,我認爲。 :)對於轉換邏輯,它取決於你在哪裏使用這些邏輯......如果它只是在視圖中,然後把它們放在輔助方法中,否則模型是一個好地方。 – Kulgar
我希望深入一點的原因之一是,在當前的實現中,錯誤消息顯示在英尺和英寸輸入之間,而不是在兩者之後,將它們移動到輔助方法不會解決這個。感謝您的意見,但! – bookcasey
如果任何人有興趣,這是一個非常頭痛的問題,我決定使用一個選擇元素,如'5'10'','5'11','6','val'設置在英寸(70,71,72),這是不難做一個小循環。 – bookcasey