Bryce
Bryce

Reputation: 2872

Rails best practice for multiple associations

I have three models in my program, in kind of a hierarchical structure:

User (has_many :computers)
Computer (has_many :programs, belongs_to :user)
Programs (belongs_to :computer)

Within the program, I have a need to see how many Programs a User has by extensions. This is pretty easy to do via User.computers.programs.

That said, would it be beneficial in any way to declare a has_many/belongs_to relationship between Users and Programs directly? Would there be any benefit (performance or otherwise), or would it just add complexity to the code?

Upvotes: 0

Views: 79

Answers (3)

Pablo Fernandez heelhook
Pablo Fernandez heelhook

Reputation: 12583

It largely depends on whether you foresee requiring to access that relationship often. If you can do without that particular query, you'll be better served to just use a

class User < ActiveRecord::Base
  has_many :computers
  has_many :programs, :through => :computers
end

and be done with it. Less code that accomplishes the same is easier to read/maintain.

But if you will be making accessing that relationship over a large dataset it might payoff to denormalize your data a bit in the way you describe in the name of saving expensive JOINs.

Upvotes: 1

Jake Dempsey
Jake Dempsey

Reputation: 6322

You could do this:

class User < ActiveRecord::Base
  has_many :computers
  has_many :programs, :through => :computers
end

That way you can just do:

user = User.first #find some user
user.programs #get a list of programs from the user through the computers they own

Upvotes: 0

blackfoks
blackfoks

Reputation: 121

There's through option:

has_many :programs, through: :computers

You can read more about it here: http://guides.rubyonrails.org/association_basics.html#the-has_many-through-association

Upvotes: 0

Related Questions