2013-08-05 28 views
0

我有一個交易控制器,具有交易的名單,我希望每個處理有3個單選按鈕之間切換「獲勝,失去了,待」。爲了實現這個目標,最好的方法是什麼?使用單選按鈕來更新數據庫

我有一對夫婦的選擇,無論是在boolean類型的交易表中創建新條目,或創建連接到交易表與中有每個選項的布爾值外鍵的不同的表。 我有點混亂..

_deal_status.html.erb

<%= form_for @deal do |f| %> 

    State: 
    <label> 
    <%= f.radio_button :state, 'pending', :class => "radio" %> 
    Pending 
    </label> 
    <label> 
    <%= f.radio_button :state, 'won', :class => "radio" %> 
    Won 
    </label> 
    <label> 
    <%= f.radio_button :state, 'lost', :class => "radio" %> 
    Lost 
    </label> 

<% end %> 

這種形式重置原始@deal形式爲nil除單選按鈕的值。

+0

如果包括_deal_status .html.erb在你的index.html.erb模板中我猜你使用''''''''''''''''''變量來處理'@ deal'變量。在index.html.erb中使用'render'deal_status'::deal => deal',在_deal_status.html.erb中使用'form_for deal'來獲得有問題的交易:) – theodorton

回答

0

聽起來像一個狀態欄是你在找什麼。如果你添加了幾個布爾列,你將會有重複的數據,因爲在任何時候都不能在兩個給定的狀態中交易(同時贏得和失去的應該是不可能的)。看看State Machines。你可以用狀態機做更高級的東西。

雖然我極力推薦它,你並不需要一個狀態機。你可以只添加一個字符串列statedeals - 表,並使用該列來跟蹤每一筆交易的狀態。

$ rails g migration add_state_to_deals state:string 

要獲取表單中的單選按鈕,你可以這樣做:

<%= form_for @deal do |f| %> 
    ... 
    State: 
    <label> 
    <%= f.radio_button :state, 'pending' %> 
    Pending 
    </label> 
    <label> 
    <%= f.radio_button :state, 'won' %> 
    Won 
    </label> 
    <label> 
    <%= f.radio_button :state, 'lost' %> 
    Lost 
    </label> 
    ... 
<% end %> 

而且有這樣的驗證和默認值二傳手在你的模型:

class Deal < ActiveRecord::Base 
    ... 
    validates_inclusion_of :state, in: %w{pending won lost} 
    after_initialize :set_default_state, if: :new_record? 

    private 

    def set_default_state 
    state = 'pending' 
    end 
    ... 
end 
+0

並且可以使用form_tag嗎? – Kmelkon

+0

這樣就夠了嗎?無需在jQuery或控制器中做任何事情?謝謝:) – Kmelkon

+0

@Kmelkon任何你想使用'form_tag'而不是'form_for'的理由? jQuery將不是必需的,但如果你想有一個默認值,你可以用JS做到這一點。優選的是在控制器或模型中設置默認值。 – theodorton