Rails: unable to set any attribute of child model
- by Bryan Roth
I'm having a problem instantiating a ListItem object with specified attributes. For some reason all attributes are set to nil even if I specify values. However, if I specify attributes for a List, they retain their values.
Attributes for a List retain their values:
>> list = List.new(:id => 20, :name => "Test List")
=> #<List id: 20, name: "Test List">
Attributes for a ListItem don't retain their values:
>> list_item = ListItem.new(:id => 17, :list_id => 20, :name => "Test Item")
=> #<ListItem id: nil, list_id: nil, name: nil>
UPDATE #1:
I thought the id was the only attribute not retaining its value but realized that setting any attribute for a ListItem gets set to nil.
list.rb:
class List < ActiveRecord::Base
    has_many :list_items, :dependent => :destroy
    accepts_nested_attributes_for :list_items, 
                                  :reject_if => lambda { |a| a[:name].blank? }, 
                                  :allow_destroy => true
end
list_item.rb:
class ListItem < ActiveRecord::Base
    belongs_to :list
    validates_presence_of :name  
end
schema.rb
ActiveRecord::Schema.define(:version => 20100506144717) do
  create_table "list_items", :force => true do |t|
    t.integer  "list_id"       
    t.string   "name"       
    t.datetime "created_at"
    t.datetime "updated_at"
  end
  create_table "lists", :force => true do |t|
    t.string   "name"        
    t.datetime "created_at"
    t.datetime "updated_at"        
  end
end