1

我有一个 simple_form 正在构建我的表单ResponseSet。响应集基本上是对调查问卷(有很多问题)的响应的集合。一个问题可以有很多答案。(这很复杂,我知道)。当尝试呈现特定问题的答案的单选按钮时,即使有与此响应相关的答案,也不会选择任何单选按钮。更改as:to:check_boxes似乎工作正常。这是一个带有 SimpleForm 的错误吗?

= simple_form_for @response_set do |rs|
  = rs.simple_fields_for :responses do |r|
    - if r.object.question.class <= Question::SingleChoice
      = r.association :answers, as: :radio_buttons, collection: r.object.question.answers, label_method: :text, label: false

response_set.rb

class ResponseSet < ActiveRecord::Base
  has_many :responses
  accepts_nested_attributes_for :responses
end

响应.rb

class Response < ActiveRecord::Base
  belongs_to :question
  has_and_belongs_to_many :answers
  belongs_to :response_set
  has_many :questions,
    through: :answers
  accepts_nested_attributes_for :answers
end

问卷调查.rb

class Questionnaire < ActiveRecord::Base
  has_many :response_sets
end

答案.rb

class Answer < ActiveRecord::Base
  has_many :responses
  belongs_to :question
end

问题.rb

class Question < ActiveRecord::Base
  has_many :responses,
    through: :answers
  has_many :answers
end
4

1 回答 1

1

尝试向:selected关联添加一个选项。例如:

= r.association :answers, 
  as: :radio_buttons, 
  collection: r.object.question.answers, 
  label_method: :text, 
  label: false, 
  selected: r.object.question.answers.select {|ans| ans.responses.any? }

此外,如果您需要构建大量问卷/调查(特别是如果它们很复杂),我是surveyor gem的忠实粉丝,即使它们的默认 CSS 很丑陋。

于 2013-09-10T20:04:21.687 回答