嵌套表单更新操作产生重复结果
在嵌套表单的更新操作期间,它似乎创建了新的嵌套记录,而不是更新当前嵌套的记录。
这就是我的控制器的样子:
class ApplicationsController "You have now applied!" end def edit @application = Application.find(params[:id]) @answers = [] @job.questions.each do |question| @application.answers.each do |answer| @answers < "You have updated your application!" end def destroy Application.find(params[:id]).destroy flash[:success] = "Application Deleted." redirect_to root_url end def show @application = Application.find(params[:id]) @answers = [] @job.questions.each do |question| @application.answers.each do |answer| @answers << answer if answer.question_id == question.id end end end private def set_user_and_job @user = current_user @job = Job.find(params[:job_id]) end def application_params params.require(:application).permit(:job_id, :user_id, answers_attributes:[:question_id, :content]).merge(user_id: current_user.id, job_id: params[:job_id]) end end
这就是我的编辑视图:
Job:
Applicant:
Edit your job application below.
"" %> question.id %>
应用程序模型本身:
# == Schema Information # # Table name: applications # # id :integer not null, primary key # user_id :integer # job_id :integer # created_at :datetime # updated_at :datetime # class Application lambda { |a| a[:content].blank? }, :allow_destroy => true def self.build(job_id) application = self.new job = Job.find(job_id) job.questions.count.times do application.answers.build end application end end
答案模型:
# == Schema Information # # Table name: answers # # id :integer not null, primary key # application_id :integer # question_id :integer # created_at :datetime # updated_at :datetime # content :string(255) # class Answer < ActiveRecord::Base belongs_to :question belongs_to :application validates :content, presence: true end
从搜索,我发现这个链接, RoR嵌套属性在编辑时产生重复 ,这表明我将:id添加到application_params,但是当我这样做时,我得到了错误
ActiveRecord::RecordNotFound in ApplicationsController#update Couldn't find Answer with ID=5 for Application with ID=17
(这也有点奇怪,因为答案的实际ID是39. 5实际上是问题的ID:S)
你对此有何看法? SO的导师,非常感谢:)
update_only不适用于has_many关系。 您需要将嵌套属性:id字段添加到您的强参数:
def application_params params.require(:application).permit(:job_id, :user_id, answers_attributes:[:id, :question_id, :content]).merge(user_id: current_user.id, job_id: params[:job_id]) end
尝试将update_only
添加到您对accepts_nested_attributes_for
的调用中。
accepts_nested_attributes_for :nested_attribute, update_only: true
- 在Rails控制器中存储对象的最佳方式(会话除外)?
- 用ruby显示日期
- AbstractController :: CommentsController中的DoubleRenderError #create
- Ruby on Rails – 创建新条目时,使用回调将两个对象在单独的表中相乘
- 通过访问原始文件覆盖rails帮助程序
- 如何在Rails 3应用程序中获取所有引擎的列表
- paperclip找不到“file.jpg”rails 4的处理程序
- 耙子流产了! Gem :: LoadError:为数据库适配器指定’postgresql’
- 一个rails应用程序,使用HTML5地理定位获取用户位置并保存到数据库