Add two foreign key columns that reference the same table

I’m still getting the same error even tho I used different names for the schema fields.

schema "users" do
    has_many :accounts, Account
    has_one :selected_account, Account, foreign_key: :selected_user_account_id
end
schema "accounts" do
    belongs_to :user, User
    belongs_to :user, User, foreign_key: :selected_user_account_id
end

The error is:

field/association :user already exists on schema, you must either remove the duplication or choose a different name

Updated
I still have the error after adding an explicit foreign_key.

schema "users" do
    has_many :accounts, Account, foreign_key: :all_user_accounts_id
    has_one :selected_account, Account, foreign_key: :selected_user_account_id
end
schema "accounts" do
    belongs_to :user, User, foreign_key: :all_user_accounts_id
    belongs_to :user, User, foreign_key: :selected_user_account_id
end

foreign_key is for the columns in the database but you also need to make sure the keys in the schema struct are unique. so instead of:

schema "accounts" do
    belongs_to :user, User, foreign_key: :all_user_accounts_id
    belongs_to :user, User, foreign_key: :selected_user_account_id
end

you need to do something like this

schema "accounts" do
    belongs_to :all_user, User, foreign_key: :all_user_accounts_id
    belongs_to :selected_user, User, foreign_key: :selected_user_account_id
end
1 Like

Thanks, your solution worked.