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?