Pla*_*Ton 19 ruby-on-rails has-one nested-attributes
我正在尝试在"问题"模型中更新嵌套的question_output属性.一个问题has_one question_output.如果数据库中没有现有的question_output,一切正常.但是如果记录已经有一个question_output,我在尝试更新时会得到以下结果:
无法删除现有的关联question_output.在将外键设置为nil之后,记录无法保存.
我本以为allow_destroy可以解决这个问题,但是唉 - 没有快乐.不可否认,我之前没有使用过has_one.但如果有人对如何解决这个问题有任何想法,我会很感激.相关代码如下:
表格:
= form_for [@question.project, @question], :as => :question, :url => admin_project_question_path(@question.project, @question) do |f|
= render '/shared/form_errors', :model => @question
= f.fields_for :question_output_attributes do |qo|
.field
= qo.label :question_type
= qo.select :question_type, QuestionOutput::QUESTION_TYPES
.field
= qo.label :client_format
= qo.select :client_format, QuestionOutput::CLIENT_FORMATS
.field
= qo.label :required
= qo.check_box :required
.field
= qo.label :min_input, 'Length'
= qo.text_field :min_length
= qo.text_field :max_length
= f.submit 'Save Question Formatting'
Run Code Online (Sandbox Code Playgroud)
问题模型:
class Question < ActiveRecord::Base
has_one :question_output
accepts_nested_attributes_for :question_output, :allow_destroy => true
end
Run Code Online (Sandbox Code Playgroud)
QuestionOutput型号:
class QuestionOutput < ActiveRecord::Base
belongs_to :question
end
Run Code Online (Sandbox Code Playgroud)
问题控制器:
class Admin::QuestionsController < ApplicationController
def show
@question = Question.find(params[:id])
@question.question_output ||= @question.build_question_output
end
def update
@question = Question.find(params[:id])
if @question.update_attributes(params[:question])
flash[:notice] = t('models.update.success', :model => "Question")
redirect_to admin_project_question_path(@question.project, @question)
else
flash[:alert] = t('models.update.failure', :model => "Question")
redirect_to admin_project_question_path(@question.project, @question)
end
end
end
Run Code Online (Sandbox Code Playgroud)
Dev*_*art 37
在您的问题模型中,将has_one行更改为:
has_one :question_output, :dependent => :destroy
Run Code Online (Sandbox Code Playgroud)
在:allow_destroy => true上accepts_nested_attributes允许您从通过问题表格中删除question_output _destroy=1HTML属性.
该:dependent => :destroy删除当你删除的问题的question_output. 或者在你的情况下删除question_output,当它被一个新的替换.
| 归档时间: |
|
| 查看次数: |
9603 次 |
| 最近记录: |