Usage has many and one association on the same model

I want my custom object to be able to be associated with many addresses and for one of those addresses to be the primary address.

I am trying to do this without using the primary address boolean notation, instead using both has-many and a-one-association - as per PinnyM's first approach in the following SO: Rails model which has both has_one and has_many, but with some restrictions

But I cannot 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 don't have access to one association. I've tried doing:

 user.primary_address
 user.addresses.primary_address 
 user.addresses.primary_address.first

      

I really don't understand how to set these associations correctly or how to refer to them. Thank your help!

+3


source to share


1 answer


Simply created models and associations that you use. I don't understand why it doesn't work in your case, because I can access the primary_address. This is the code I am using to access it using the rails console. Note. I created a user and a couple of addresses beforehand.

# 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 these calls, though:

user.addresses.primary_address 
user.addresses.primary_address.first

      

+2


source







All Articles