Ruby on rails 轨道4-can和x27;t连接到rails 4上数据库上的表

Ruby on rails 轨道4-can和x27;t连接到rails 4上数据库上的表,ruby-on-rails,ruby,sqlite,ruby-on-rails-4,Ruby On Rails,Ruby,Sqlite,Ruby On Rails 4,我正在按照教程学习如何使用嵌套属性,我正在做一个调查,但有点不对劲,因为我无法在问题表中插入任何数据 我就是这么做的: 问题模型 class Question < ActiveRecord::Base belongs_to :survey has_many :answers, dependent: :destroy end 现在,当我单击“提交”时,只保存调查名称,但不保存任何问题!! 像这样: 2.1.1 :023 > Question.all Question

我正在按照教程学习如何使用嵌套属性,我正在做一个调查,但有点不对劲,因为我无法在问题表中插入任何数据

我就是这么做的:

问题模型

class Question < ActiveRecord::Base
    belongs_to :survey
    has_many :answers, dependent: :destroy
end

现在,当我单击“提交”时,只保存调查名称,但不保存任何问题!! 像这样:

2.1.1 :023 > Question.all
Question Load (0.3ms)  SELECT "questions".* FROM "questions"
=> #<ActiveRecord::Relation []>


我添加了另一个模型[答案]

class Answer < ActiveRecord::Base
  belongs_to :question
end
现在是前面的问题和答案 我应该如何处理强参数

应该是这样吗

def survey_params
  params.require(:survey).permit(:name, answers_attributes: [:content]) 
end

听起来您的调查允许的参数中没有列出
questions\u属性

确保您的
调查参数包含问题属性,如:

private

def survey_params
  params.require(:survey).permit(:name, questions_attributes: [:content]) 
end
如果您有其他调查属性或问题属性,则需要在此处也允许它们


您可以发布“创建”操作吗?如果你使用强参数,还有“def survey_params”的定义,你有没有尝试过没有3次?@StavrosSouvatzis我添加了创建action@MohamedElMahallawy同样的问题,高级版谢谢:)@StavrosSouvatzis如果你是对的,“def survey_params”不见了。。。非常感谢:)我添加了另一个名为answer的模型,我有同样的问题,我应该如何处理它?我把代码放在问题中它起作用了:)我把它改成了这个def survey_params.require(:survey)。permit(:name,questions_attributes:[:content,:id,:survey_id,answers_attributes:[:content,:id,:questions_id]])end
# POST /surveys
# POST /surveys.json
def create
@survey = Survey.new(survey_params)

respond_to do |format|
  if @survey.save
    format.html { redirect_to @survey, notice: 'Survey was successfully created.' }
    format.json { render action: 'show', status: :created, location: @survey }
  else
    format.html { render action: 'new' }
    format.json { render json: @survey.errors, status: :unprocessable_entity }
  end
end
end
 private
# Use callbacks to share common setup or constraints between actions.
def set_survey
  @survey = Survey.find(params[:id])
end

# Never trust parameters from the scary internet, only allow the white list through.
def survey_params
  params.require(:survey).permit(:name)
end
end
class Answer < ActiveRecord::Base
  belongs_to :question
end
class Question < ActiveRecord::Base
belongs_to :survey
has_many :answers, dependent: :destroy
accepts_nested_attributes_for :answers, :reject_if => lambda { |a| a[:content].blank? }, allow_destroy: true
end
# GET /surveys/new
def new
@survey = Survey.new
1.times do
question = @ survey.questions.build
2.times { question.answers.build }
end
end 
def survey_params
  params.require(:survey).permit(:name, answers_attributes: [:content]) 
end
private

def survey_params
  params.require(:survey).permit(:name, questions_attributes: [:content]) 
end