[ActiveRecord] scope for collection associations

In Rails 4 you should be able to do:

class Post
  has_many :comments, -> { visible }
end

@Jon Leighton

Can that scope be removed later? Can I retrieve all comments, including hidden ones?

@Dheeraj if you need two associations to the same model with different scopes, you could just create another association for each one that is needed, e.g.

class Post
has_many :comments, -> { visible }
has_many :unscoped_comments, class_name: ‘Comment’
end

However, I wouldn’t rely on having multiple associations with different scopes, etc. too much. Going beyond scoping, lets consider the association’s “include” option. Let’s say that you use include in the association to help avoid n+1 queries that you are seeing. You do this because the show method is loading associations. But when you add that, you forget that index didn’t need those associations. This could significantly increase time to perform an index action. So, in the “lets just add a new association” mentality, you try to have one association that uses include and one that doesn’t- except that won’t work, because either the association is eagerly included or it isn’t. So, instead of using include on the association in the model, you end up with Comment.all for the index method and Comment.where(…).includes(…).first in the show method. Why not leave as much as you can in the controller that relates to those queries in the individual action methods from the beginning?

except that won’t work, because either the association is eagerly included or it isn’t.

self-correction: You could have an association that defined include and another that didn’t to the same model- it isn’t eager loading just because you defined another association that uses the include option. But the end result is the same- you likely end up defining the include in the controller in one action method and not the other.

Hi Gary,

You’re right. I understand that they should be left in the controller as much as possible.

Thank you for the detailed scenario and the explanations! They were very helpful :slight_smile: