Rails - one user address with multiple addresses

I have 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 address model

 class Address < ActiveRecord::Base attr_accessible :country_id, :city, :plz, :street, :streetnr, :first_name, :last_name end 

What I want to do with active record associations: each user has billing_address and sending_address. Can I create a relationship to access them, like user.billing_address?

+4
source share
2 answers

You can add the class name and foreign key to the 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 
+6
source

The method mentioned by @kengo should work, but a more proper way would be

 class User < ActiveRecord::Base attr_attr_accessible :email, :password, :password_confirmation, :remember_me, :first_name, :last_name, :shipping_address_attributes; :billing_address_attributes has_one :billing_address, :class_name => 'Address' has_one :shipping_address, :class_name => 'Address' accepts_nested_attributes_for :billing_address accepts_nested_attributes_for :shipping_address end 

This way you can have nested forms for accepting values ​​for your shipping and billing addresses. In addition, you will have your basic requirement.

+1
source

Source: https://habr.com/ru/post/1487393/


All Articles