Has_only_one or has_mate

Hello fellow Railers,

I wonder if somebody implemented such behaviour already:

maria.friend = peter

and then automatically this would happen with peter

peter.friend = maria


maria.friend = nil

would set whatever maria.friend was before to nil too, so:
peter.friend = nil

Does anybody know how I could extend has_one to such has_only_one

Thanks, folks!

has_one means that the entity has 0 or 1. It is a “has only one.”

It looks like you’re trying a self-referencing relationship. Make sure
Person (assuming) model has both has_one and belongs_to methods.

Something like:

has_one :friend, :class => ‘Person’
belongs_to :person

Derek Perrault wrote:


has_one :friend, :class => ‘Person’
belongs_to :person, :foreign_key => ‘friend’

I will try this, thanks Derek!


has_one :friend, :class => ‘Person’
belongs_to :person, :foreign_key => ‘friend’

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs