-1

I'm new to rails. I have 2 existing models that I want to establish a 1 to 1 relationship.

class User
  has_one :info

class Info
  belongs_to :user

My Question is do I need to create foreign keys for each of them? My end goal is to just access info via: @user.info.

smathy
  • 26,283
  • 5
  • 48
  • 68
SpongebobJunior
  • 601
  • 1
  • 9
  • 24
  • No, only one table needs a foreign key, but you'll need some index on the database to enforce the 1-1 relationship, see here for e.g: https://stackoverflow.com/a/15284858/828193 – user000001 Mar 01 '19 at 17:52

2 Answers2

1

As the commenter said, no you don't. Only the belongs_to side needs a foreign key. Let me point you to the Rails guides for this particular issue, but more widely they're excellent resources for this type of information.

smathy
  • 26,283
  • 5
  • 48
  • 68
0

Start with simple.

@user = User.new
@user.first_name = "john"
@user.save

info = @user.info
info.address = "Some address"
info.save

@user.reload

puts @user.info.address

PS: I really suggest to start with a few video tutorials and just repeat what people are doing in video

Igor Kasyanchuk
  • 766
  • 6
  • 12