Justin Meltzer
Justin Meltzer

Reputation: 13558

Rails checkboxes

I have a string column in my database which is either "artist" or "listener", and I want the user to be able to choose which string the column is populated with by clicking the appropriate checkbox. How would I do this?

Upvotes: 2

Views: 713

Answers (3)

Marcel Jackwerth
Marcel Jackwerth

Reputation: 54782

You should use radio-buttons for that matter. Also make sure to put that logic into the model (validations).

# 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 %>

Upvotes: 1

fl00r
fl00r

Reputation: 83680

You should use radio button here:

# 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 %>

Upvotes: 2

Dylan Markow
Dylan Markow

Reputation: 124449

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

This would make my_field be "artist" when it's checked, and "listener" when unchecked.

Upvotes: 1

Related Questions