Shagy Moe wrote:
> I've got some code that more or less looks like this:
>
> class Project < ActiveRecord::Base
>
> def create_new_document
>
> document = Document.new
>
> document.attributes = { "project_id" => self.id,
> "attribute2" => "etc..."}
>
> if document.save
> new_document_page = DocumentPage.new
>
> new_document_page.attributes = { "document_id" => new_document.id,
> "attribute2" => "etc..." }
>
> new_document_page.save
> end
> end
> end
>
> So, the strange thing is that even though the document.save call is
> sometimes failing and is wrapped in an "if" statement, it still tries to
> create the document page which ,of course, causes DB error since the
> new_document.id is nil. Also, I get "Mysql::Error: Cannot add or update
> a child row: a foreign key constraint fails" on the Project update sql
> because the document_id is the actual object_id instead of the id. The
> update statement is trying to put a value like "-618357298" instead of
> the document id (which doesn't exist since it didn't get saved.
Is new_document.id a typo? It should be document.id.
The fact that you're getting the object_id does mean that
the object is not a model instance.
Let AR take care of setting the foreign key:
document.pages.create!(:attribute2 => "etc...") if document.save
--
Rails Wheels - Find Plugins, List & Sell Plugins - http://railswheels.com
--~--~---------~--~----~------------~-------~--~----~
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
-~----------~----~----~----~------~----~------~--~---