使用Rails进行多选选择创建操作

我有一个Collection_select,Multiple设置为true

#views/courses/new true,:size => 8,:class=> "text")%> 

在我的模型中

 #deparment Model has_many :courses #Course Model belongs_to :deparment 

我想要一种情况,如果课程有多个部门从多选列表中选择,则此详细信息将保存在课程表中。 我的当前实施只保存了第一个选定的课程部门,并丢弃其余部分。 请问我该如何做到这一点。

 def create @course = Course.new(params[:course] || []) if @course.save redirect_to courses_path, :notice => "Course Created Successfully" else redirect_to new_course_path flash[:alert] = "Error Creating Course" end end 

谢谢

首先要做的事情……你应该有这样的联想。

department.rb

 has_and_belongs_to_many :courses 

course.rb

 has_and_belongs_to_many :departments 

而且你可以拥有像这样的观点/课程/新

 <%=text_field_tag :course_name)%> <%=select_tag(:departments, options_from_collection_for_select(Department.all, :id, :name),:multiple =>true,:size => 8,:class=> "text")%> 

并且创建动作将是这样的。

 def create @course = Course.new(params[:course_name] || []) if @course.save params[:departments].split(',').each do |id| @course.departments << Department.find(id) end redirect_to courses_path, :notice => "Course Created Successfully" else redirect_to new_course_path flash[:alert] = "Error Creating Course" end end 

迁移加入表

 class CreateCoursesDepartments < ActiveRecord::Migration def change create_table :courses_departments do |t| t.integer :course_id t.integer :department_id end end end 

对于两个对象,您将需要一个Has And Belongs To Many(HABTM)关联。 看看这个:

http://guides.rubyonrails.org/association_basics.html#the-has_and_belongs_to_many-association