steven_noble
steven_noble

Reputation: 4213

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?

Upvotes: 0

Views: 4921

Answers (3)

jokklan
jokklan

Reputation: 3550

You must remove the each call in the end so you just have:

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

Update:

You should also use @survey.results.sort{...} instead of f.object.results.sort{...}. This reads better and is more effective. Try to avoid f.object when possible :)

Upvotes: 2

steven_noble
steven_noble

Reputation: 4213

Was able to achieve the desired result by ditching nested attributes altogether and using:

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

Upvotes: 0

Shamir K.
Shamir K.

Reputation: 395

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'

Upvotes: 0

Related Questions