Forum: Ruby on Rails select html for habtm

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
45196398e9685000d195ec626d477f0e?d=identicon&s=25 Trans (Guest)
on 2007-04-08 02:47
(Received via mailing list)
How does one use a <select> for a habtm field? I'm having trouble
getting it to work.

Here's my html:

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

And my controller:

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

  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
      render :action => 'edit'

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,

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

This topic is locked and can not be replied to.