Multiple Select with Rails Create Action

半世苍凉 提交于 2019-12-11 10:52:02

问题


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")%>

in My Models

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

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

Thank You


回答1:


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")%>

and create action will be like this.

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

migration for joining table

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

    end
  end
end



回答2:


You will need a Has And Belongs To Many (HABTM) association for both your objects. Take a look at this:

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



来源:https://stackoverflow.com/questions/15223560/multiple-select-with-rails-create-action

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!