Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Naming polymorphic relationships well

This question is about the naming style of polymorphic relationships.

My database has three types of person: a 'Company', a Client, and an Employee. Each of the three are in polymorphic relationships with tasks and events, and projects.

According to the Rails guides, this would be done like (I've omitted some classes for brevity):

Person.rb
has_many :tasks, :as => :taskable
has_many :events, :as => :eventable
has_many :projects, :as => :projectable # awkward names

Task.rb
belongs_to :taskable, :polymorphic => true

These lead to the rather strange:
@person = @task.taskable

I feel that the following would be far more grammatical and elegant... would it work, and if so, is there a reason that official sources use words like projectable rather than words like owner?

Person.rb
has_many :tasks, :as => :owner
has_many :events, :as => :owner
has_many :projects, :as => :owner

Task.rb
belongs_to :owner, :polymorphic => true

This creates the elegant:
@person_1 = @task.owner
@person_2 = @project.owner
like image 815
sscirrus Avatar asked Apr 13 '12 08:04

sscirrus


1 Answers

I personally try to keep it as generic as possible.

So :as => :owner does make more sense to me.

In case of doubt, I'd just use

:as => :parent

which I've already seen in some projects.

like image 69
Radi Avatar answered Oct 09 '22 07:10

Radi