Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - One User multiple Addresses

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?

like image 406
Evo_x Avatar asked Mar 23 '23 11:03

Evo_x


1 Answers

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
like image 172
kengo Avatar answered Apr 05 '23 04:04

kengo