如何使simple_form呈现我的嵌套属性

时间:2013-05-10 07:30:40

标签: ruby-on-rails simple-form nested-attributes

调查&结果如下链接:

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>

我如何实现我的想法?

3 个答案:

答案 0 :(得分: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:)

答案 1 :(得分: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'

答案 2 :(得分:0)

通过完全抛弃嵌套属性并使用:

,能够达到预期的效果
= f.collection_radio_buttons :result_ids, @survey.results, :id, :name