8

I have two models, for example User and Club with their attributes:

User:
  id
  uid
  email
  etc.

and

Club:
  id
  player_id
  address
  supporter
  etc.

For some reason, the join attribute is clubs.player_id with users.uid NOT clubs.player_id with users.id. Is it possible connecting these two model with one-to-one association using has_one and belongs_to? thx

raymondralibi
  • 1,933
  • 1
  • 17
  • 25

2 Answers2

27

I bet this would work:

class User < ActiveRecord::Base
  has_one :club, :foreign_key => :player_id, :primary_key => :uid
end

class Club < ActiveRecord::Base
  belongs_to :user, :foreign_key => :player_id, :primary_key => :uid
end
fny
  • 31,255
  • 16
  • 96
  • 127
Adam
  • 3,148
  • 19
  • 20
0

Can Clubs have many Users and Users belong to many Clubs? If so, you may want to look at the http://guides.rubyonrails.org/association_basics.html page for the has_and_belongs_to_many relationship association method. If you use this association method, you will need to create a separate migration table to relate the user_id with the club_id.

Rebekah Waterbury
  • 22,236
  • 5
  • 23
  • 28
  • FYI, you cannot use `:primary_key` for `has_and_belongs_to_many` relationships, so if you require that, you'll *need* to use a `has_many :through` relationship. – Joshua Pinter Aug 26 '14 at 20:51