On Rails 2.1.1, I have this simple case:

class Post < ActiveRecord::Base
  has_many :comments
end

class Comment < ActiveRecord::Base
  belongs_to :post
  validates_presence_of :post_id
end

Now, when building associated comments to an unsaved post, the
validation fails:

p = Post.new
=> #<Post id: nil, name: nil, created_at: nil, updated_at: nil>

c = p.comments.build
=> #<Comment id: nil, text: nil, comment_id: nil, created_at: nil,
updated_at: nil>

c.valid?
=> false

c.errors
=> #<ActiveRecord::Errors:0x23f8d18 @base=#<Comment id: nil, text:
nil, comment_id: nil, created_at: nil, updated_at: nil>,
@errors={"post_id"=>["can't be blank"]}>

According to http://dev.rubyonrails.org/ticket/4147,
validates_presence_of the foreign key is the proper way to validate
the presence associated objects. However, the documentation warning
regarding this was later removed.

So, question is: How do I validate the presence of associated objects,
while still allowing the building of associated objects to an unsaved
model?

Regards,

Christian
--~--~---------~--~----~------------~-------~--~----~
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