2011-03-27 68 views
2

我在我的數據庫中有一個「藝術家」或「偵聽器」的字符串列,我希望用戶能夠通過單擊相應的複選框來選擇填充該列的字符串。我將如何做到這一點?Rails複選框

回答

2

您應該使用這裏的單選按鈕:

# Imagine it is User model and user_type field 
<%= form_for User.new do |f| %> 
    <%= f.radio_button :user_type, "artist" %> 
    <%= f.radio_button :user_type, "listener" %> 
<% end %> 
+0

除了「type」屬性在我的個人資料模型中:P – 2011-03-27 21:19:50

+0

我不知道它在哪裏。所以你可以使用任何型號 – fl00r 2011-03-27 21:20:22

+0

,我不建議你在你的數據庫中使用單詞'type' :) – fl00r 2011-03-27 21:21:01

1

f.check_box :my_field, {}, "artist", "listener"

這將使my_field是「藝術家」時,它的檢查,「監聽器」時選中。

+0

這會使一個複選框? – 2011-03-27 21:20:29

+0

是的,如果你想看到兩個選項,你應該使用單選按鈕,而不是複選框。 – 2011-03-27 21:21:10

+0

ahh okk謝謝... – 2011-03-27 21:21:39

1

您應該使用單選按鈕爲這一問題。還要確保將該邏輯放入模型中(驗證)。

# model 
class User 
    TYPES = %w(artist listener) 

    validates_inclusion_of :user_type, :in => TYPES 
end 

# view 
<%= form_for :user do |f| %> 
    <% User::TYPES.each do |type| %> 
    <%= f.radio_button :user_type, type %> 
    <% end %> 
<% end %> 
+1

更好一點'validates:user_type,:inclusion => {:in => TYPES}':) – fl00r 2011-03-27 21:32:25