使用Rails创建操作的多选

时间:2013-03-05 12:14:51

标签: ruby-on-rails ruby-on-rails-3 rails-activerecord

我有一个Collection_select,其中Multiple设置为true

 #views/courses/new
<%=collection_select(:course, :department_id, Department.all, :id, :name, {},
:multiple =>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

谢谢

2 个答案:

答案 0 :(得分:0)

对于您的对象,您将需要一个拥有和属于多人(HABTM)的关联。看看这个:

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

答案 1 :(得分:0)

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

<强> department.rb

has_and_belongs_to_many :courses

<强> course.rb

has_and_belongs_to_many :departments

并且您可以像这样拥有 views / courses / new

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