0

调查和结果链接如下:

class Survey < ActiveRecord::Base
  has_many :results
  accepts_nested_attributes_for :results
end

class Result < ActiveRecord::Base
  belongs_to :survey
end

结果在其表中有以下列:

create_table "results", :force => true do |t|
  t.integer  "survey_id"
  t.integer  "field_id"
  t.boolean  "selected",      :default => false
end

它还具有以下虚拟属性:

class Result < ActiveRecord::Base
  def name
    self.field.name.gsub("{{input}}", self.input)
  end
end

我希望我的调查表列出我的结果,从最高点结果到最低点结果。

每个结果都应该绑定到一个单选框,以便一次只能有一个结果为真。

到目前为止,我的表单如下所示:

= simple_form_for [@competitor, @survey] do |f|
  = f.simple_fields_for :result, f.object.results.sort{ |a,b| b.points <=> a.points}.each do |r|
    = r.input :selected, :label => r.object.name
  = f.button :submit, :id => 'submit_survey'

对于我的麻烦,我收到以下错误:

undefined method `name' for #<Enumerator:0x007fb8075d3038>

我怎样才能实现我的想法?

4

3 回答 3

2

您必须最终删除each呼叫,以便您拥有:

= simple_form_for [@competitor, @survey] do |f|
  = f.simple_fields_for :result, f.object.results.sort{ |a,b| b.points <=> a.points} do |r|
    = r.input :selected, :label => r.object.name
  = f.button :submit, :id => 'submit_survey'

simple_fields_for自动运行每个。

更新:

您还应该使用@survey.results.sort{...}而不是f.object.results.sort{...}. 这读起来更好,更有效。尽量避免f.object:)

于 2013-05-10T08:50:02.343 回答
0

能够通过完全放弃嵌套属性并使用:

= f.collection_radio_buttons :result_ids, @survey.results, :id, :name
于 2013-05-10T09:05:19.153 回答
0

迭代结果应该是这样的,但我不确定它是否足以制作收音机

= simple_form_for [@competitor, @survey] do |f|
  - @survey.results.sort{ |a,b| b.points <=> a.points}.each do |result|
    = f.simple_fields_for result do |r|
      = r.input :selected, :label => result.name
  = f.button :submit, :id => 'submit_survey'
于 2013-05-10T08:59:37.433 回答