Rails 在表单中保存用户选择的外键

Rails Saving User Selected Foreign Key In Form

我是 Rails 的新手,我一直在为这个无法克服的想法而苦苦挣扎。例如我有

class Survey < ActiveRecord::Base
    has_many :questions
end

class Question < ActiveRecord::Base
   belongs_to :survey
end

我创建了一组调查。现在我想创建一些问题并通过其外键 survey_id 将其分配给调查。在问题 new.html.erb 页面中,我使用了高级表格来显示调查 ID(我遵循 this tutorial)。它工作正常但是,当我单击提交时,survey_id 似乎没有保存。

这是我的question_controller.rb

def create
@question = Question.create(question_params)

respond_to do |format|
  if @question.save
    format.html { redirect_to @question, notice: 'Question was successfully created.' }
  else
    format.html { render :new }
  end
end

def question_params
  params.require(:question).permit(:description, :date_created, :survey_id)
end

表格如下:

<%= form_for(@question) do |f| %>
    <div class="field">
       <%= f.label :survey_id %><br>
       <%= collection_select(:question, :survey_id, Survey.all, :id, :description, prompt: true ) %>
    </div>
<% end %>

我知道为了让它工作,我必须做类似的事情

@question = @survey.questions.create(...)

但我不知道如何在用户单击下拉列表和 select 适当的调查之前获取 @survey 实例。

有人知道怎么做吗??

您已经创建了调查对象并希望它们与问题相关联,

因此,如果您使用 select 下拉菜单将调查名称设为 select,那么在您的问题表单中,将 select 选项值设置为调查 ID 。因此您的 question params 将包含 survey_id 参数,其值等于 selected 调查的 ID。因此 Question.create(question_params) 将使用 survey_id.

创建问题

你的创建方法应该是

def create
 @survey = Survey.find(params[:survey_id])
 @question = @survey.questions.create(question_params)

 respond_to do |format|
  if @question.save
   format.html { redirect_to @question, notice: 'Question was successfully created.' }
  else
   format.html { render :new }
 end
end

或者您也可以使用过滤器

  class QuestionsController < ApplicationController
      before_filter :set_survey, only: :create

     def create
      @question = @survey.questions.create(question_params)

     respond_to do |format|
       if @question.save
         format.html { redirect_to @question, notice: 'Question was successfully created.' }
       else
        format.html { render :new }
       end
      end

      private
        def set_survey
           @survey = Survey.find(params[:survey_id]) || Survey.new
        end  

    end