简体   繁体   中英

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?

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

I would just go for class methods and leave scopes behind. The syntax is much simpler because it's just like any other class method, including passing parameters to it.

Try:

def self.live
  where( is_deleted: 0, sent_to_api: 1 )
end

And then:

project.videos.live.size

and see if it helps.

For more info, read here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM