使用 Rails 创建操作进行多项选择 [英] Multiple Select with Rails Create Action
本文介绍了使用 Rails 创建操作进行多项选择的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个 Collection_select,Multiple 设置为 true
I have a Collection_select, with Multiple set to 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
我想要一种情况,如果一门课程从多选列表中选择了多个部门,则此详细信息将保存在课程表中.My Current Implementation 仅保存课程的第一个选定部门,并丢弃其余部门.请问我如何实现这一点.
I want a situation such that if a course has more than one department selected from the Multiple select list, this details is saved in the course Table. My Current Implementation saves just the first selected department for a course, and discards the rest. Please how do i achieve this.
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
谢谢
推荐答案
首先..你应该有这样的关联.
First thing first.. You should have associations like this.
department.rb
has_and_belongs_to_many :courses
course.rb
has_and_belongs_to_many :departments
而且您可以拥有这样的视图/课程/新.
and than you can have views/courses/new like this.
<%=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
这篇关于使用 Rails 创建操作进行多项选择的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文