Home > Net >  How to differentiate similar has_many :through associations in Rails?
How to differentiate similar has_many :through associations in Rails?

Time:11-18

I'll start off with my models:

class Project < ApplicationRecord
  has_many :permissions
  has_many :wallets, through: :permissions

  has_many :follows
  has_many :wallets, through: :follows
end

class Permission < ApplicationRecord
  belongs_to :project
  belongs_to :wallet
end

class Follow < ApplicationRecord
  belongs_to :project
  belongs_to :wallet
end

class Wallet < ApplicationRecord
  has_many :permissions
  has_many :projects, through: :permissions

  has_many :follows
  has_many :projects, through: :follows
end

As you can see, Permission and Follow are both through associations for Projects and Wallets.

They serve different purposes (Permission gives Wallets access to manage Projects while Follow lets Wallets "follow" projects for updates).

So how can I differentiate them? For example, if I do Wallet.find(1).projects, it defaults to using the "Follow" model...though in some scenarios I'd want it to actually use the "Permission" model.

CodePudding user response:

Believe you'd find it will default to the has_many :projects that is defined last.

Need to give the associations different names, which will require something like ...

class Wallet < ApplicationRecord
  has_many :permissions
  has_many :projects, through: :permissions

  has_many :follows
  has_many :follow_projects, through: :follows, source: :project
end
  • Related