Skip to content

Instantly share code, notes, and snippets.

@jpowers
Created December 1, 2011 21:34
Show Gist options
  • Save jpowers/1420039 to your computer and use it in GitHub Desktop.
Save jpowers/1420039 to your computer and use it in GitHub Desktop.
inverse_of for in memory association access
class Shipment < ActiveRecord::Base
has_many :labels
accepts_nested_attributes_for :labels
end
class Label < ActiveRecord::Base
belongs_to :shipment
end
ruby-1.9.2-p180 :001 > s = Shipment.new(:vendor_service_code =>'asdasd', "labels_attributes"=>{"0"=>{"package_weight"=>"1", "insured_value"=>"50"}})
=> #<Shipment id: nil, user_id: nil, state: "processing", ref_1: nil, ref_2: nil, po_number: nil, total_weight: 1.0, package_count: 1, residential: false, return_label: false, vendor_service_code: "asdasd", vendor_error_message: nil, ship_at: nil, created_at: nil, updated_at: nil, no_courier: false, vendor_package_code: "YOUR_PACKAGING", insured_value: 50, cod: nil, cod_amount: nil, cod_type: nil>
ruby-1.9.2-p180 :002 > s.labels.first.shipment.vendor_service_code
NoMethodError: undefined method 'vendor_service_code' for nil:NilClass
*** Ahhh inverse_of.....
class Shipment < ActiveRecord::Base
has_many :labels, :inverse_of => :shipment
accepts_nested_attributes_for :labels
end
class Label < ActiveRecord::Base
belongs_to :shipment, :inverse_of => :label
end
ruby-1.9.2-p180 :013 > s = Shipment.new(:vendor_service_code =>'asdasd', "labels_attributes"=>{"0"=>{"package_weight"=>"1", "insured_value"=>"50"}})
=> #<Shipment id: nil, user_id: nil, state: "processing", ref_1: nil, ref_2: nil, po_number: nil, total_weight: 1.0, package_count: 1, residential: false, return_label: false, vendor_service_code: "asdasd", vendor_error_message: nil, ship_at: nil, created_at: nil, updated_at: nil, no_courier: false, vendor_package_code: "YOUR_PACKAGING", insured_value: 50, cod: nil, cod_amount: nil, cod_type: nil>
ruby-1.9.2-p180 :014 > s.labels.first.shipment.vendor_service_code
=> "asdasd"
ruby-1.9.2-p180 :015 >
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment