簡體   English   中英

帶有嵌套屬性的Rails 3模型不更新子級

[英]Rails 3 model with accepts nested attributes not updating children

我有一個模型設置,用戶可以創建一個包含很多問題和每個問題很多答案的測驗

這些模型如下所示:

model Page < AR::Base

end

model Quiz < Page
  has_many :questions
  accepts_nested_attributes_for :questions, :allow_destroy => true
end

model Question < AR::Base
  belongs_to :quiz
  has_many :answers
  accepts_nested_attributes_for :answers, :allow_destroy => true
end

model Answer < AR::Base
  belongs_to :question
end

我的表格如下所示:

= form_for @quiz do |f|

  f.fields_for :questions do |qf|
    # fields omitted, have fields for id, content, etc
    qf.fields_for :answers do |af|
      # fields omitted, have fields for id, answer, etc
  f.submit 'save'

當我僅編輯測驗或添加新的問題和答案時,一切工作都很棒,但是當我編輯現有的問題和答案時,更改不會持久保存在數據庫中。 我可以看到正確的嵌套參數已發送到控制器中,並且在調用update_attributes后檢查@quiz時,它會顯示已更新的問題和答案,但是在頁面更新后這些問題和答案將不會保留。

我以前從未遇到過此類問題,並且很難找到原因,有人可以分享一些見解嗎?

謝謝!

根據要求,控制器代碼:(Quiz是Page的STI子類)

PagesController < ApplicationController
  def update
    @page = @section.pages.find(params[:id])

    if @page.update_attributes(params[@page.type.downcase.underscore])
      redirect_to online_course_section_pages_path(@online_course, @section), :notice => "Your page has been updated"
    else
      render :edit
    end
  end
end

編輯:

發現問題是因為使用@page.type.downcase.underscore而不是@page.type.underscore.downcase所以更新屬性被傳遞為nil而不是實際數據

發現問題是因為使用@ page.type.downcase.underscore而不是@page.type.underscore.downcase所以更新屬性被傳遞為nil而不是實際數據

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM