I got a User model
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :shipping_address_id; :billing_address_id
end
and an Address model
class Address < ActiveRecord::Base
attr_accessible :country_id, :city, :plz, :street, :streetnr, :first_name, :last_name
end
What I want to do via active record associations: Each user has a billing_address and a shipping_address. Can I create a relation so I can access these like user.billing_address?
You can add class name and foreign key in belongs_to association.
class User < ActiveRecord::Base
attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :shipping_address_id; :billing_address_id
belongs_to :billing_address, class_name: :Address, foreign_key: :billing_address_id
belongs_to :shipping_address, class_name: :Address, foreign_key: :shipping_address_id
end
Then you can access addresses like
user.billing_address
user.shipping_address
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With