Rails: Modeling an optional relation in ActiveRecord
Posted
by
Hassinus
on Stack Overflow
See other posts from Stack Overflow
or by Hassinus
Published on 2012-10-03T15:30:50Z
Indexed on
2012/10/03
15:37 UTC
Read the original article
Hit count: 144
ruby-on-rails
|activerecord
I would like to map a relation between two Rails models, where one side can be optionnal. Let's me be more precise...
I have two models: Profile
that stores user profile information (name, age,...) and User
model that stores user access to the application (email, password,...).
To give you more information, User
model is handled by Devise gem for signup/signin.
Here is the scenario of my app:
1/ When a user register, a new row is created in User
table and there is an equivalent in Profile
table. This leads to the following script:
class User < ActiveRecord::Base
belongs_to :profile
end
2/ A user can create it's profile without registering (kind of public profile with public information), so a row in Profile
doesn't have necessarily a User
row equivalent (here is the optional relation, the 0..1
relation in UML).
Question: What is the corresponding script to put in class Profile < AR::Base
to map optionally with User
?
Thanks in advance.
© Stack Overflow or respective owner