如何在控制器中为使用连接表的提交表单编写create方法?

时间:2015-03-16 15:42:16

标签: ruby-on-rails ruby

我正在尝试创建一个允许调用提交的表单。我已经创建了所有适当的MVC。然后我创建了一个名为问题的模型,并使用主动管理员来允许管理员用户在他们认为合适时向表单添加新问题。当我测试提交表单时,我收到此错误

undefined method `each' for nil:NilClass
    @submit = Submit.new(submit_params)
@submit.save
params[:submit][:question_ids].each do |question_id|
  @question = Question.find(question_id)
  @submit.questions << @question
end

这是我提交的控制器:

class SubmitsController < ApplicationController
before_action :set_submit, only: [:show, :edit, :update, :destroy]

 def index
  @submits = Submit.all
 end

 def show
 end


 def new
  @submit = Submit.new
  @questions = Question.all
end


 def edit
 end


 def create
   @submit = Submit.new(submit_params)
   @submit.save
    params[:submit][:question_ids].each do |question_id|
     @question = Question.find(question_id)
     @submit.questions << @question
   end

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


 def update
   respond_to do |format|
     if @submit.update(submit_params)
       format.html { redirect_to @submit, notice: 'Application was successfully updated.' }
       format.json { render :show, status: :ok, location: @submit }
     else
       format.html { render :edit }
        format.json { render json: @submit.errors, status: :unprocessable_entity }
      end
    end
  end

 def destroy
   @submit.destroy
   respond_to do |format|
      format.html { redirect_to submits_url, notice: 'Submit was successfully destroyed.' }
     format.json { head :no_content }
    end
  end

这是我的提交和问题模型:

提交:

class Submit < ActiveRecord::Base
  has_and_belongs_to_many :questions

  belongs_to :user
end

问题:

class Question < ActiveRecord::Base
  has_and_belongs_to_many :submits
end

我确定我的控制器中存在某种语法错误,但我不知道是什么。使用连接表还是一个新手。任何帮助/解释将非常感激。

谢谢!

1 个答案:

答案 0 :(得分:2)

你不需要这个

params[:submit][:question_ids].each do |question_id|
  @question = Question.find(question_id)
  @submit.questions << @question
end

我没有看到你的提交参数,但是如果你在允许的参数中添加问题ID,那么rails会在它自己的联接表中构建条目。

def submit_params
  params.require(:submit).permit(:user_id, question_ids: [])
end