simple_form关联未按预期工作

时间:2013-09-03 17:59:44

标签: ruby-on-rails ruby ruby-on-rails-4 simple-form

我有一个simple_form正在构建ResponseSet的表单。响应集基本上是对问卷的回答的集合(其中有很多问题)。一个问题可以有很多答案。 (这很复杂,我知道)。当试图渲染单选按钮以获得特定问题的答案时,即使存在与此响应相关的答案,也不会选择任何单选按钮。将as:更改为: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

response.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

questionnaire.rb

class Questionnaire < ActiveRecord::Base
  has_many :response_sets
end

answer.rb

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

question.rb

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

1 个答案:

答案 0 :(得分: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很难看。