Optional belongs_to relationship in Ruby -


i'm migrating application on ror php defines object, let's call document can created user either registered user of application, or anonymous user gives email address (in case without associated user account). there no requirement visitor create user account, should still have ability create document.

in model, first led create document model references user belongs_to association. not case. in pure sql , php not hard, although comes it's own challenges, model in "purest" ruby/rails way.

if visitor not have associated user, email address stored directly against document object.

to start discussion, here snippets each model.

# user.rb class user < activerecord::base   has_many :documents end  # document.rb class document < activerecord::base   attr_accessible :title, :description, :email_address    belongs_to :user end 

my goal able retrieve user documents using standard dot notation:

user.documents 

and check reverse relationship see if document belongs user or if contains email address.

if document.user.nil? ...  if document.email_address.nil? ... 

i have read on has_one relationship not sure if right path go down.

any or suggestions appreciated, thanks!

you might want consider making user class more flexible supports anonymous users , stores email address.

it might make code bit cleaner.


Comments

Popular posts from this blog

c# - How to set Z index when using WPF DrawingContext? -

razor - Is this a bug in WebMatrix PageData? -

visual c++ - Using relative values in array sorting ( asm ) -