I want my user object to be able to be associated with many addresses, and for one of those addresses to be the primary address.
I'm trying to do this without using a Boolean to denote the primary address, instead using both a has-many and and a has-one association - as per the first approach by PinnyM in the following SO: Rails model that has both 'has_one' and 'has_many' but with some contraints
But I can't seem to get it to work.
My migrations:
class User < ActiveRecord::Migration
def change
create_table(:users) do |t|
t.integer :primary_address_id
t.string :name
end
end
end
class Address < ActiveRecord::Migration
def change
create_table(:addresses) do |t|
t.integer :user_id
t.string :address
end
end
end
My models:
class User
has_many :addresses
has_one :primary_address, :class_name => "Address"
end
class Address
belongs_to :user
has_one :user
end
This allows me to use the has_many association by doing user.addresses but I can't seem to access to has one association. I've tried doing:
user.primary_address
user.addresses.primary_address
user.addresses.primary_address.first
I don't really understand how to set these associations up correctly or how to access them. Would appreciate your help!