4

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!

Community
  • 1
  • 1
user3711600
  • 853
  • 3
  • 12
  • 27

1 Answers1

2

Just created models and associations that you are using. I don't see why it is not working in your case, because I can access primary_address. This is the code I am using to access it using rails console. Note: I have created a User and couple of Addresses in advance.

# in case if you have user with id = 1    
User.find(1).primary_address
# or another example
User.first.primary_address

I don't think your associations will allow this calls though:

user.addresses.primary_address 
user.addresses.primary_address.first
  • Ah that makes sense. I was just accessing them incorrectly. I don't really understand the set up of the has_one association for primary address. Why is there a has_one on both the User and Address model? A has_one on Address and a belongs_to on User would make more sense to me. Any ideas why it's set up this way? – user3711600 Sep 25 '14 at 03:41
  • Actually, you don't really need has_one in Address model in this particular case. You need belongs_to in order to do something like Address.first.user (access user that address belongs to), but has_one is not needed. I wasn't using it while testing. That is also because not every address is going to be primary address. – Djafar Hodi-Zoda Sep 25 '14 at 04:09