select html for habtm

How does one use a <select> for a habtm field? I'm having trouble getting it to work.

Here's my html:

  <div>     <p><label for="projects">Project</label><br/>     <select id="schedule_projects" name="schedule[project_ids]" multiple="multiple" size="10">       <%= options_from_collection_for_select(@all_projects, :id, :name, @selected_projects) %>     </select>     </p>   </div>

And my controller:

  def edit     @schedule = Schedule.find(params[:id])     @all_projects = Project.find(:all, :order=>"name")     @selected_projects = @schedule.projects.collect{|prj| prj.project_id.to_i}   end

  def update     @schedule = Schedule.find(params[:id])     if @schedule.update_attributes(params[:schedule])       flash[:notice] = 'Schedule was successfully updated.'       redirect_to :action => 'show', :id => @schedule     else       render :action => 'edit'     end   end

I keep getting an error:

  ActiveRecord::StatementInvalid in ScheduleController#update

  Mysql::Error: Duplicate entry '3' for key 1: INSERT INTO projects_schedules (`project_id`, `id`, `schedule_id`) VALUES (3, 3, 1)

It's because the id 3 is already used in the projects_schedules table. Why is it choosing a duplicate key?

T.