简体   繁体   English

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

[英]How to make simple_form present my nested attributes

survey & result are linked like this: 调查和结果如下链接:

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

class Result < ActiveRecord::Base
  belongs_to :survey
end

result has the following columns in its table: 结果在其表中有以下列:

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

It also has the following virtual attribute: 它还具有以下虚拟属性:

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

I want my form for survey to list my results, from the highest point result to the lowest point result. 我希望我的调查表能够列出我的结果,从最高点结果到最低点结果。

Each result should be tied to a radio box so that only one can be true at a time. 每个结果都应该绑在一个收音机盒上,这样一次只能有一个。

So far, my form looks like this: 到目前为止,我的表单看起来像这样:

= 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'

For my trouble, I'm getting the following error: 对于我的麻烦,我收到以下错误:

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

How can I achieve what I have in mind? 我怎样才能实现我的想法?

You must remove the each call in the end so you just have: 您必须在最后删除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 run through each automatically. simple_fields_for自动运行每个。

Update: 更新:

You should also use @survey.results.sort{...} instead of f.object.results.sort{...} . 您还应该使用@survey.results.sort{...}而不是f.object.results.sort{...} This reads better and is more effective. 这读起来更好,更有效。 Try to avoid f.object when possible :) 尽可能避免使用f.object :)

Iterating over results should look like this, but I'm not sure if it's enough to make radios 迭代结果应该是这样的,但我不确定它是否足以制作无线电

= 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'

能够通过完全抛弃嵌套属性并使用以下方法来实现所需的结果:

= f.collection_radio_buttons :result_ids, @survey.results, :id, :name

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM