Stephen Lead
Stephen Lead

Reputation: 1976

How to navigate nested HABTM relationships?

In my application:

So a user may own multiple events, each of which has many videos, and the user accordingly owns the combined total of those events' videos.

Given a user, how can I obtain their videos?

I'm currently using this cumbersome workaround:

@events = @user.events
@videos = []
@events.map do |event|
  event.videos.map do |video|
    @videos.push(video)
  end
end

Is there a better and more efficient way to obtain that user's videos? As you can maybe tell I'm a Rails noob...

Upvotes: 1

Views: 50

Answers (1)

Taryn East
Taryn East

Reputation: 27747

Try setting up a "through" association:

class User
  has_and_belongs_to_many :events
  has_many :videos, :through => :events

you should now be able to:

user.videos

Heaps more detail on associations in the really-you-should-read-them-all Rails guides: http://guides.rubyonrails.org/association_basics.html :)


Other random notes (mainly because you have self-described as a noob, and I taught this stuff for a while) ;)

1) you probably don't need the @ in front of your rails variable names... you only need to call a variable @something if you are in the controller, and passing the variable to the view... otherwise you can just call it something

2) you really only need to use map if you're actually doing something the with end result eg:

other_numbers = [1,2,3].map {|num| num + 1 }

if you're not going to assign the result of map to something... then it's generally better to just use each eg:

events.each do |event|
  ...

3) in your loop, you grab an array event.videos then add each video individually to another array with @videos.push, but you can just add arrays together eg:

@videos = []
events.each do |event|
  @videos += event.videos
end

Upvotes: 2

Related Questions