如何为has_and_belongs_to_many关系创建下拉列表



这是我的模型:

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

在我的控制器中,用于编辑论文组:

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

在我看来,我需要能够看到N个下拉列表;1个与当前论文组关系中的每个学生。

我尝试了以下方法,但出现错误,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>

我需要为学生选择 N 个元素,并且在编辑此表单时将先前选择的元素显示为已选择。Rails有办法解决这个问题吗?

我可以循环访问student_ids集合和类似的东西吗:

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

ThesisGroup模型中accepts_nested_attributes_for :students

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

编辑:我突然不太确定collection_select中的参数:(

相关内容

  • 没有找到相关文章

最新更新