Reputation: 1233
I've seen many similar questions, and looked at the answers, but nothing seems to be helping me and I've been working on this for a while now. The error is 'Can't convert symbol into integer'. My goal is to be able to create multiple sub_groups for each race. I'm just starting with trying to create one for the time being. Here's the relevant code...
** UPDATE **
VIEW
<%= simple_form_for(@race, :url => form_path, :method => form_method, :html => { :class =>
'form-horizontal form-compressed' }) do |f| %>
<fieldset>
<%= f.simple_fields_for :sub_groups do |g| %>
<%= g.input :name, requred: false %>
<%= g.collection_radio_buttons :discount_type,
[['dollars', '$'], ['percent', '%']], :first, :last %>
<%= g.input :discount_amount, :as => :integer, required: false %>
<% end %>
<hr/>
** RACE MODEL**
class Race < ActiveRecord::Base
has_many :sub_groups
accepts_nested_attributes_for :sub_groups
attr_accessible :sub_groups_attributes
** SUB_GROUP MODEL **
class SubGroup < ActiveRecord::Base
belongs_to :race
has_many :race_users
attr_accessible :discount_amount, :discount_type, :display_results, :name
end
PARAMS after my code update...
Parameters: {"utf8"=>"✓",
"authenticity_token"=>"VihBL4TDT/Lte4YBji/4fp4XvOri1UgUZ8B33wQuCko=", "race"=>
{"sub_group"=>{"name"=>"dfd", "discount_type"=>"dollars", "discount_amount"=>"2"}},
"commit"=>"Next", "wizard"=>"2", "id"=>"13-test5"}
CONTROLLER
class RacesController < ApplicationController
def new
@race = Race.new
@sub_groups = @race.sub_groups.build
@wizard_step = -1
@wizard_step_name = Race.wizard_step_name_from_id @wizard_step
@wizard_mode = true
render :layout => "race_wizard"
end
def update
@race = Race.find params[:id]
@wizard_step = params[:wizard].to_i + 1
@race.wizard_step = @wizard_step
@race.update_attributes(params[:race])
end
So I took advice from answer 1, and switched to using :sub_groups in the view. Now I have a new problem, which is the sub-group fields don't show up at all, despite the fact that I built a sub_groups thing in the #new method. I'm really stumped on how I can make this happen. This is driving me bonkers. Any help is much appreciated. Thanks!
Upvotes: 0
Views: 1151
Reputation: 44715
The way fields_for works is that if you supply a symbol it checks whether your model respond to {given_symbol}_attributes=
. If it does the name of sub-fields is {given symbol}_attributes
, otherwise just {given_symbol}
.
What you need is to add accepts_nested_attributes_for :sub_groups
to your Race model. This methods will create a default setter sub_groups_attributes=
, which will make fields_for :sub_groups
to generate fields with name sub_groups_attributes
.
You can also write your own sub_groups_attributes=
method, but you need to be sure you know what you're doing there as it might be a little tricky to debug.
Note, that fields_to :sub_groups
won't display fields if there are no sub_group associated with given object - you will need to build one in your controller first.
Upvotes: 1