2011-03-27 73 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