以下是我的模特:
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
在我的控制器中,用于编辑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
在我的视图中,我需要能够看到N个下拉列表;每个学生与当前的ThesisGroup建立关系。
我尝试了以下操作,但收到错误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 %>
答案 0 :(得分:0)
您的accepts_nested_attributes_for :students
模型中需要ThesisGroup
。
<%= 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中的参数不太确定:(