rails 3中的多对多关系

时间:2013-07-05 11:33:34

标签: ruby-on-rails

我想在我的两个模型之间创建多对多关系:用户和教师。我通过创建第三个表使用has_manythrough关系创建了关系。在该表中,我有两列:user_idteacher_id。现在我在某些变量中有useridteacherid。我已通过addteacher方法将其存储在第三个表中,但我想使用关联将user_idteacher_id存储在第三个表中。我怎么能这样做?

class TeachersController < ApplicationController

  def index
    @teachers = Teacher.all

    respond_to do |format|
      format.html # index.html.erb
      format.json { render json: @teachers }
    end
  end


  def show
    @teacher = Teacher.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render json: @teacher }
    end
  end


  def new
    @teacher = Teacher.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render json: @teacher }
    end
  end


  def edit
    @teacher = Teacher.find(params[:id])
  end


  def create
    @teacher = Teacher.new(params[:teacher])

    respond_to do |format|
      if @teacher.save
        format.html { redirect_to @teacher, notice: 'Teacher was successfully created.' }
        format.json { render json: @teacher, status: :created, location: @teacher }
      else
        format.html { render action: "new" }
        format.json { render json: @teacher.errors, status: :unprocessable_entity }
      end
    end
  end


  def update
    @teacher = Teacher.find(params[:id])

    respond_to do |format|
      if @teacher.update_attributes(params[:teacher])
        format.html { redirect_to @teacher, notice: 'Teacher was successfully updated.' }
        format.json { head :no_content }
      else
        format.html { render action: "edit" }
        format.json { render json: @teacher.errors, status: :unprocessable_entity }
      end
    end
  end


  def destroy
    @teacher = Teacher.find(params[:id])
    @teacher.destroy

    respond_to do |format|
      format.html { redirect_to teachers_url }
      format.json { head :no_content }
    end
  end

  def chooseteacher
    @teachers = Teacher.all
  end

  def addteacher
    debugger
    @teachers = params[:teachers_ids]


    if @teachers==nil
       redirect_to home_welcome_path
    else
      @userid = current_user.id
      @teachers.each do |teacher|
      @dc= UserTeacher.create(:user_id => @userid , :teacher_id => teacher) end
      if @dc.save
        redirect_to home_welcome_path
      end
    end
  end
end

0 个答案:

没有答案