DEV Community

Aniket Bhattacharyea
Aniket Bhattacharyea

Posted on

Help needed in figuring out Rails association

I have two models - User and Network. In my case, each User can have many Network and each Network can have many User and belongs to one User (the one who created).

For example, let's say there is user1 with two networks N1 and N2. The network N1 has user2 and the network N2 has user3.

What I want to achieve is the creator field of N1 and N2 will give me user1 and the users field of N1 will give me [user2] and that of N2 will give me [user3]

So far, it's ok. I can have the creator field with foreign_key, and I can use a has_many through relation to figure out which networks contain which users and which users belong to which networks.

But in that case, is there a way to quickly tell if there is a relation between two users or not?

For example something like user2.follows? user1 will return true since user2 belongs to a network of user1. I can iterate through all the networks created by user1 and check if user2 belongs to it, but is there a better way?

Discussion (4)

Collapse
thorstenhirsch profile image
Thorsten Hirsch • Edited on

I'm not sure if you're searching for a network that user2 is following, which has been created by user1 (easy) or if you're searching for a network that both users are following (a bit harder).

easy task
user2.networks.where(creator: user1)

a bit harder task
I think the solution is described here: coderwall.com/p/9xk6ra/rails-filte...
So in your case it might look like this: user1.networks.merge(user2.networks)

In both cases the database does the hard work, so no need for iterating through all networks thus shooting N queries at the database.

Collapse
heraldofsolace profile image
Aniket Bhattacharyea Author

In the first case user2.networks will give a list of networks he has created, but it seems like the way to go. I can have user2.followed_networks for that. Thanks

Collapse
thorstenhirsch profile image
Thorsten Hirsch

It's a bit different than you think. user2.networks does only return a list of networks when executed, because networks is not an array. It is an ActiveRecord::Relation. That's why user1.networks.merge(user2.networks) does something completely different than iterating through the networks.

Thread Thread
heraldofsolace profile image
Aniket Bhattacharyea Author

I understand. What I wanted to say was that user2.networks is the list of networks user2 has created, not the ones he's following.