I have some trouble solving a problem.
I’m trying to make a musician community, where you’ll be able to find
other musicians. The users will have to choose which kind of music style
they prefer, and which instruments they play. They should be able to
choose more than one style and instrument, so i think ill use check
boxes, but theres my problem how? I’ve tries check_box and
check_box_tag, but i dont really know how to use them. I have values for
the check boxes in VALID_STYLES, and would like to use some kind of
loop, so i dont have to repeat code. another problem is that I can get
one checkbox to work but not 2 or more, when i select multible
checkboxes only the value of the first gets stored in the DB
Model:
[code=]class Spec < ActiveRecord::Base
belongs_to :user
VALID_GENDERS = [“Mand”, “Kvinde”]
VALID_AREAS = ["",“København”, “Storkøbenhavn”, “Ã…rhus”, “Aalborg”,
“Odense”,
“Nordsjælland”, “Vestsjælland”, “Sydsjælland”,
“Midtsjælland”,
“Lolland/Falster”, “Fyn”, “Nordjylland”, “Østjylland”,
“Vestjylland”, “Midtjylland”, “Sønderjylland”,
“Bornholm”,
“Andet” ]
VALID_STYLES = [“Rock”, “Pop”, “Elektronisk”, “Hip-Hop”, “R&B og
Soul”,
“Metal”, “Blues”, “Jazz”, “Verdensmusik”,
“Country”,
“Folkemusik”, “Klassisk”]
START_YEAR = 1900
VALID_DATES = DateTime.new(START_YEAR)…DateTime.now
ZIP_CODE_LENGTH = 4
validates_inclusion_of :gender,
:in => VALID_GENDERS,
:allow_nil => true,
:message => “skal være mand eller kvinde”
validates_inclusion_of :birthdate,
:in => VALID_DATES,
:allow_nil => true,
:message => “er ugyldig”
validates_inclusion_of :area,
:in => VALID_AREAS,
:allow_nil => true,
:message => “skal ikke være opdigtet”
validates_format_of :zip_code, :with =>
/(^$|^[0-9]{#{ZIP_CODE_LENGTH}}$)/,
:message => “skal være pÃ¥ 4 tegn”
end[/code]
Controller:
[code=]def edit
@title = “Opdater info”
@user = User.find(session[:user_id])
@user.spec ||= Spec.new
@spec = @user.spec
if param_posted?(:spec)
if @user.spec.update_attributes(params[:spec])
flash[:notice] = “Ændringer gemt”
redirect_to :controller => “user”, :action => “index”
end
end
end[/code]
View:
[code=]<% form_for :spec do |form| %>
<%= @title %><%= error_messages_for ‘spec’ %>
<%= text_field_for form, “zip_code”, Spec::ZIP_CODE_LENGTH %>
<%= submit_tag “Update”, :class => “submit” %>
<% end %>[/code] Migrate: [code=]class CreateSpecs < ActiveRecord::Migration def self.up create_table :specs do |t| t.column :user_id, :integer, :null => false
t.column :gender, :string
t.column :birthdate, :date
t.column :area, :string, :default => ""
t.column :zip_code, :string, :default => ""
t.column :music_style, :mediumtext, :default => ""
# t.column :music_instruments, :mediumtext, :default => ""
# t.column :looking_for, :mediumtext, :default => ""
end
end
def self.down
drop_table :specs
end
end[/code]
Please help a noob
Regards Benjamin