如何更新嵌套资源Rails 4

时间:2015-08-22 12:19:57

标签: ruby-on-rails-4

我有模特 - 测试,问题和教师答案。

test.rb

class Question < ActiveRecord::Base
  belongs_to :test
  has_many :teacher_answers, dependent: :destroy
  accepts_nested_attributes_for :teacher_answers
end

question.rb

class TeacherAnswer < ActiveRecord::Base
  belongs_to :question
end

teacher_answer.rb

---    
standard scaffold code
---
def test_params
      params.require(:test).permit(:title, 
                                    questions_attributes: [:question_text, :test_id, teacher_answers_attributes: [:teacher_answer_text, :correct, :question_id]],)
    end

和控制器 test_controller.rb

---    
standard scaffold code
---
def question_params
      params.require(:question).permit(:question_text, :test_id,
                                        teacher_answers_attributes: [:teacher_answer_text, :correct, :question_id])
    end

question_controller.rb

`<span class="my_tag">#tag</span>`

使用问题和答案创建新测试时,它会正确创建所有内容,但在更新时:

  1. 无法移除问题
  2. 保存时不更新问题和答案,但保存新旧问题,即用2个问题更新测试时,保存后会有4个问题。

2 个答案:

答案 0 :(得分:1)

您应该允许:id :_destroy中的test_paramsupdate允许deletedef test_params params.require(:test).permit(:title, questions_attributes: [:id, :question_text, :test_id, :_destroy, teacher_answers_attributes: [:id, :teacher_answer_text, :correct, :question_id, :_destroy]]) end 正常工作。

allow_destroy: true

<强> 更新

您还应为test.rbquestion.rb

添加class Test < ActiveRecord::Base has_many :questions, dependent: :destroy accepts_nested_attributes_for :questions, allow_destroy: true end class Question < ActiveRecord::Base belongs_to :test has_many :teacher_answers, dependent: :destroy accepts_nested_attributes_for :teacher_answers, allow_destroy: true end
{{1}}

答案 1 :(得分:0)

  1. accepted_nested_attributes_for默认情况下不允许删除,请使用delete:true
  2. 通过隐藏标记
  3. 将ID传递给表单