Search code examples
htmlrubyruby-on-rails-3modelhas-and-belongs-to-many

How can I create a drop down for a has_and_belongs_to_many relationship?


Here are my models:

class ThesisGroup < ActiveRecord::Base
  belongs_to :course
  has_and_belongs_to_many :students

  attr_accessible :code, :title, :course_id
end

class Student < ActiveRecord::Base
  has_and_belongs_to_many :thesis_groups

  attr_accessible :email, :lastnames, :names
end

class CreateThesisGroupStudentJoinTable < ActiveRecord::Migration  
  def change
    create_table :thesis_groups_students, :id => false do |t|
      t.integer :thesis_group_id
      t.integer :student_id
    end
  end
end

And in my controller, for the editing of ThesisGroups:

def update
    @thesis_group = ThesisGroup.find(params[:id])

    respond_to do |format|
      if @thesis_group.update_attributes(params[:thesis_group])
        format.html { redirect_to @thesis_group, notice: 'Thesis group was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @thesis_group.errors, status: :unprocessable_entity }
      end
    end
  end

In my View, I need to able to see N drop down lists; 1 for each student in the relationship with this current ThesisGroup.

I tried the following but get an error, undefined method map for #<ThesisGroup:0x007f76b8c9d4d0>:

<div class="control-group">
  <%= f.label :student %>
  <div class="controls">
    <%= f.collection_select 'student_ids', @thesis_group, :id, :names %>
  </div>
</div>

I need to have N select elements for students and when editing this form have the previously selected elements displayed as selected. Does Rails have some way of handling this?

Can I iterate through the student_ids collection and something like:

<%= student_ids.each do |s| %>
  generate html select element with 's'
<% end %>

Solution

  • You'll need accepts_nested_attributes_for :students in your ThesisGroup model.

    <%= field_set_tag 'Alumnos' do %>
      <%= f.fields_for :students do |student| %>
        <%= student.label :name, 'Student' %>
        <%= student.collection_select :student_id, Student.all, :id, :name %>
      <% end %>
    <% end %>
    

    Edit: I'm suddenly not too sure about the parameters in collection_select either :(