[LRUG] Binding the creation of 2+ objects together
Kenneth Lee
kenfodder at gmail.com
Thu Jul 31 10:28:23 PDT 2008
Here's a quick demo of validates_associated that I was convincing myself
of it working...
class Vehicle < ActiveRecord::Base
has_one :registration, :dependent => :destroy
validates_presence_of :name
validates_associated :registration
def before_validation_on_create
self.registration = Registration.new()
end
end
class Registration < ActiveRecord::Base
belongs_to :vehicle
validates_presence_of :number_plate
end
In the console:
>> Vehicle.destroy_all
=> []
>> Registration.destroy_all
=> []
>> v = Vehicle.create
=> #<Vehicle id: nil, name: nil, created_at: nil, updated_at: nil>
>> v.errors
=> #<ActiveRecord::Errors:0x1868e80 @base=#<Vehicle id: nil, name: nil,
created_at: nil, updated_at: nil>, @errors={"name"=>["can't be blank"],
"registration"=>["is invalid"]}>
>> Vehicle.count
=> 0
>> Registration.count
=> 0
>> v = Vehicle.create :name => 'cheese'
=> #<Vehicle id: nil, name: "cheese", created_at: nil, updated_at: nil>
>> v.errors
=> #<ActiveRecord::Errors:0x1829078 @base=#<Vehicle id: nil, name:
"cheese", created_at: nil, updated_at: nil>,
@errors={"registration"=>["is invalid"]}>
>> v.registration.errors
=> #<ActiveRecord::Errors:0x18283f8 @base=#<Registration id: nil,
number_plate: nil, vehicle_id: nil, created_at: nil, updated_at: nil>,
@errors={"number_plate"=>["can't be blank"]}>
>> Vehicle.count
=> 0
>> Registration.count
=> 0
>> _
Obviously this will always be the case until I initialize it with a
number_plate, but you get the general idea.
Anthony Green wrote:
> Has anyone encountered a situation in which the business rules state that a
> object can't be saved unless its twin is saved too ?
>
> I'm seeing this is pattern repeated where an object with a has_one
> relationship to a twin is created but you need to check its twin has created
> as well and that both will save. You can't create one entry in a table
> without a corresponding entry in a different table.
>
> Does anyone know of an extension to the association declaration that
> enforces these kind of rules. A source of creation version of :dependent =>
> :destroy
>
> Tony
>
>
> _______________________________________________
> Chat mailing list
> Chat at lists.lrug.org
> http://lists.lrug.org/listinfo.cgi/chat-lrug.org
>
>
More information about the Chat
mailing list