Question from a relative newbie. I have the following models (rails -v
Rails 2.3.8)

class Node < ActiveRecord::Base
   belongs_to :containable, :polymorphic => true
end

class Root < ActiveRecord::Base
  has_one :node, :as => :containable

  validates_presence_of :owner
  validates_numericality_of :owner, :only_integer => true, :message =>
"can only be whole number."
  validates_inclusion_of :owner, :in => 21..30, :message => "can only
be between 21 and 30."
end

Now, from the console:
>> n=Node.new(:containable=>Root.new(:owner=>22), :name=>"aaabz")
=> #<Node id: nil, parent_id: nil, lft: nil, rgt: nil, containable_id:
nil, containable_type: "Root", name: "aaa", permissions: "none",
created_at: nil, updated_at: nil>
>> n.save
=> true
=> #<Node id: 66, parent_id: nil, lft: 7, rgt: 8, containable_id: 10,
containable_type: "Root", name: "aaabz", permissions: "none",
created_at: "2010-07-13 13:55:35", updated_at: "2010-07-13 13:55:35">
>> Root.find(10)
=> #<Root id: 10, owner: 22, created_at: "2010-07-13 13:55:35",
updated_at: "2010-07-13 13:55:35">

I did not realize that both records (Node and the containable) would
automatically be saved to the db when the container (Node) was saved,
but it was a nice bonus. So this was all ok with me.

HOWEVER,  the following  also occurred:
>> n=Node.new(:containable=>Root.new(:owner=>1), :name=>"aaab")
=> #<Node id: nil, parent_id: nil, lft: nil, rgt: nil, containable_id:
nil, containable_type: "Root", name: "aaab", permissions: "none",
created_at: nil, updated_at: nil>
>> n.save
=> true
>> n
=> #<Node id: 65, parent_id: nil, lft: 5, rgt: 6, containable_id: nil,
containable_type: "Root", name: "aaab", permissions: "none",
created_at: "2010-07-13 13:47:19", updated_at: "2010-07-13 13:47:19">

That is, the containable record failed to validate, so it was not
saved, while the container was ok and it WAS saved, leaving things in
quite an unexpected condition.

I know I can code around this, but it seems quite odd. Am I missing
something simple?

Thanks.

-- 
You received this message because you are subscribed to the Google Groups "Ruby 
on Rails: Talk" group.
To post to this group, send email to [email protected].
To unsubscribe from this group, send email to 
[email protected].
For more options, visit this group at 
http://groups.google.com/group/rubyonrails-talk?hl=en.

Reply via email to