views:

377

answers:

1

Hi,

I have a teacher profile model which has many subjects (separate model). I want to add subjects to the profile on the same form for creating/editing a profile. I'm using accepts_nested_attributes for and this works fine for creation. However on the edit page I am getting a very strange error - instead of seeing 3 subjects (I added three at create and a look into the console confirms this), I see 12 subjects(!).

#Profile model

class Profile < ActiveRecord::Base    

   has_many :subjects
   accepts_nested_attributes_for :subjects  

end

#Subject Model

class Subject < ActiveRecord::Base

 belongs_to :profile

end                 

#Profile Controller (only showing deviations from normal RESTFUL setup)

def new
 @profile = Profile.new
  3.times do
  @profile.subjects.build
 end  
 end


#Here's 1 of three parts of the subject output of = debug @profile
  errors: !ruby/object:ActiveRecord::Errors 
      base: *id004
      errors: !map:ActiveSupport::OrderedHash {}

    subjects: 
    - &id001 !ruby/object:Subject 
      attributes: 
        exam: Either
        name: "7"
        created_at: 2010-04-15 10:38:13
        updated_at: 2010-04-15 10:38:13
        level: Either
        id: "31"
        profile_id: "3"
      attributes_cache: {}

 #  Note that 3 of these attributes are displayed despite me seeing 12 subjects on screen

Other info in case it's relevant.

Rails: 2.3.5, Ruby 1.8.7 p149, HAML, inherited_resources

I've never had so much difficulty with a bug before - I've already lost about 8 hours to it. Would really appreciate any help!

Thanks to any courageous takers

Jack

+1  A: 

Turns out it was an issue with the edit form. I had accidentally set the nested fields block as (fields_for) as inserted ruby rather than evaluated ruby .

Thus instead of writing this


   - form.fields_for :subjects do |ff|
    = ff.collection_select :name, Subject.all, :id, :name, :include_blank => true
    = ff.select :exam, ["Either", "Leaving Cert Only"] 
    = ff.select :level, ["Either", "Higher Level Only"]     

I wrote this:


   = form.fields_for :subjects do |ff|
    = ff.collection_select :name, Subject.all, :id, :name, :include_blank => true
    = ff.select :exam, ["Either", "Leaving Cert Only"] 
    = ff.select :level, ["Either", "Higher Level Only"]

Jack Kinsella