Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 4: how to use named scope with has_many associations

In my Rails 4 app Project (model) has_many Videos (model). I have a named scope in the videos model:

scope :live, where( is_deleted: 0, sent_to_api: 1 )

In one of my project views, I do this (project is an instance of Project):

project.videos.live.size

What I expect to get is the number of projects in that specific project but instead I get the number of videos in any project. It's as if .live is not returning a subset from .videos but rather replacing it.

I see it explained here that chaining named scopes with one another should be combined with logical AND but when applied to an "association method" [<--not sure the proper terminology for .videos in this context] that doesn't seem to be happening.

What's the right way to do this?

like image 279
emersonthis Avatar asked Sep 13 '13 17:09

emersonthis


Video Answer


1 Answers

I believe it should read like this in Rails 4:

scope :live, -> { where(is_deleted: 0, sent_to_api: 1) }

The rails 4 docs and all examples in it show you passing in a callable object to the scope to ensure it gets called each time. If it doesn't work like this try implementing it as a class method and see how that works out for you.

http://api.rubyonrails.org/classes/ActiveRecord/Scoping/Named/ClassMethods.html

like image 158
Mike Waldrup Avatar answered Nov 15 '22 14:11

Mike Waldrup