我是Rails的新手,并且基于此构建了一些内容,但它需要较小的更新,使其与Rails 4的强大参数兼容:
http://railscasts.com/episodes/196-nested-model-form-part-1
我将这个调查的参数列入白皮书,基于类似的帖子提出了问题和答案:
Rails 4 Nested Attributes Unpermitted Parameters
class Survey < ActiveRecord::Base has_many :questions,:dependent => :destroy accepts_nested_attributes_for :questions,allow_destroy: true end class Question < ActiveRecord::Base belongs_to :survey has_many :answers,:dependent => :destroy accepts_nested_attributes_for :answers,allow_destroy: true end class Answer < ActiveRecord::Base belongs_to :question end class SurveysController < ApplicationController def survey_params params.require(:survey).permit(:name,questions_attributes: [:id,:survey_id,:content]) end class QuestionsController < ApplicationController def question_params params.require(:question).permit(:survey_id,:content,answers_attributes: [:id,:question_id,:content]) end class AnswersController < ApplicationController def answer_params params.require(:answer).permit(:question_id,:content) end
第一个嵌套模型(问题)工作,但第二个(答案)返回错误,当我提交主要的调查表单:
未经许可的参数:answers_attributes
Started POST "/surveys" for 127.0.0.1 at 2013-07-10 19:20:00 +0800 Processing by SurveysController#create as HTML Parameters: {"utf8"=>"✓","authenticity_token"=>"pCK7j73kJPmld6gMXtbnBcheHU3pb9FGdjbHJPX6leE=","survey"=>{"name"=>"test","questions_attributes"=>{"0"=>{"content"=>"bbb","answers_attributes"=>{"0"=>{"content"=>"bbbb"}}}}},"commit"=>"Create Survey"} Unpermitted parameters: answers_attributes
我检查了数据库,数据不存在,并在日志中发现错误.第一套嵌套数据(问题)在那里并且工作,只有第二个不是.我也有:id在那里人们说你也需要.
据我所知,每个父母都需要将修改的直接嵌套属性列入白名单.我使用完全相同的代码来获得问题的工作,但答案不是被列入白名单,即使我已经这样做的问题.
任何指针赞赏.我似乎找不到任何双嵌套的例子来看.
更新:我通过反复修正了问题.
我发现修复是白名单需要匹配属性的嵌套.所以要修复以上我改变了这一点:
class SurveysController < ApplicationController def survey_params params.require(:survey).permit(:name,:content]) end
到这个:
class SurveysController < ApplicationController def survey_params params.require(:survey).permit(:name,:content]]) end