以单一形式多次创建一个模型

时间:2018-05-16 12:32:21

标签: ruby-on-rails parameters controller

你好我正在为调查建立ROR调查申请表。我遇到了将多个对象保存到我的数据库中的问题。提交后我的参数看起来都很好,但却出现错误:

undefined method许可证'对于#Array:0x00007ff29d873010`

我的参数看起来像

Parameters: {
  "utf8"=>"✓", 
  "authenticity_token"=>"vdUPSIU43ex1Wx3qZB4Xr6qNEaG0FbEyK2tkJ9OCcAtxK3jHe5lKVohS9JFOdpx/cISwIvzAKTRGw5zxUUS4QA==", 
  "survey_response"=>[
    {"user_id"=>"1", "survey_question_id"=>"22", "answer"=>"Hello"}, 
    {"user_id"=>"1", "survey_question_id"=>"23", "answer"=>"Hello"}], 
  "commit"=>"Create Survey response"
}

我的survey_response_params方法是

def survey_response_params
  params.require(:survey_response).permit(:answer, :survey_question_id, :user_id, :survey_answer_id)
end

我的控制器如下:

class SurveyResponsesController < ApplicationController

def index
@survey_responses = SurveyResponse.all
end

def show
end

def new
@survey_response = SurveyResponse.new
@survey = Survey.find(1)
@survey_questions = @survey.survey_questions
end

def edit
@survey = Survey.find(1)
@survey_questions = @survey.survey_questions
end

def create
@survey_response = SurveyResponse.new(survey_response_params)

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

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

def destroy
@survey_response.destroy
respond_to do |format|
  format.html { redirect_to survey_responses_url, notice: 'Survey response was successfully destroyed.' }
  format.json { head :no_content }
end
end

private
# Use callbacks to share common setup or constraints between actions.
def set_survey_response
  @survey_response = SurveyResponse.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def survey_response_params
  params.permit(survey_response: [:answer, :survey_question_id, :user_id, :survey_answer_id])
end
end

模型

class SurveyResponse < ApplicationRecord
belongs_to :survey_question
belongs_to :user
end

1 个答案:

答案 0 :(得分:0)

您需要更改强大的参数,对于数组看起来像:

def survey_response_params
  params.permit(survey_response: [:answer, :survey_question_id, :user_id, :survey_answer_id])
end

更新:

我对你的模型和控制器一无所知,但我认为在控制器中它应该是这样的

survey_response_params[:survey_response].each do |attrs|
  SurveyResponse.new(attrs)
end