← Back to Upcase

Naming associations rules


(Mike Cheverda) #1

I always have problems naming things, as most of you i think)

And today I was working on has many through association.

First version of association:

class User < ActiveRecord::Base
  has_many :subscriptions, foreign_key: :subscriber_id
  has_many :toolset_subscriptions, through: :subscriptions, source: :item
end

class Toolset < ActiveRecord::Base
  has_many :subscriptions, foreign_key: :item_id, dependent: :destroy
  has_many :subscribers, through: :subscriptions, source: :subscriber
end

class Subscription < ActiveRecord::Base
  belongs_to :subscriber, class_name: 'User'
  belongs_to :item, class_name: 'Toolset', counter_cache: true
end

Second version of association:

class User < ActiveRecord::Base
  has_many :subscriptions
  has_many :toolset_subscriptions, through: :subscriptions, source: :toolset
end

class Toolset < ActiveRecord::Base
  has_many :subscriptions, dependent: :destroy
  has_many :subscribers, through: :subscriptions, source: :user
end

class Subscription < ActiveRecord::Base
  belongs_to :user
  belongs_to :toolset, counter_cache: true
end

I think both ways are good and could be used. Like it, because it could be more easily extended to polymorphic association by adding ‘item_type’ column, and ‘subscriber’ association is more descriptive then just ‘user’

But second version is more straight forward and easier to set up. And I don’t think i would need polymorphic association anytime soon for a project.

What version do you think is better? Are there any general rules for something like this?


(Jason Draper) #2

I have a few thoughts on this but I’m not sure there are any hard rules for this sort of thing.

My first thought is that I prefer to be more descriptive when possible, even if it requires a line or two of extra configuration. More configuration is not going to hurt you but when someone else tries to understand your models, poor naming can hurt. I don’t think that user is a ‘bad’ name but subscriber is definitely more clear.

Using subscriber defines what the relationship is, not who it is applies to and I think that is a win.