I'm having a problem instantiating a ListItem
object with specified attributes. For some reason all attributes are set 开发者_StackOverflowto 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
.
UPDATE #2:
I added validates_associated :list_items
to the List
class which alleviated an error regarding the name
attribute being blank.
However, I still can't explicitly assign an id
to a new ListItem
.
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
I created your models and tables in my local setup. I didn't encounter any errors. There must be some class name conflict OR you have some before_save filters/observers resetting the values.
Note
I would change the model names to be bit more specific. It is very easy to run in to class name conflicts with names like List
and ListItem
Hmm,
I've encountered something similar when validations don't work properly. Try
ListItem.create!(:id => 17, :list_id => 20, :name => "Test Item")
This should give you more direct feedback if the model is invalid.
精彩评论