Ruby-on-rails Rails 4:如何使用具有 has_many 关联的命名范围

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18792180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 22:42:41  来源:igfitidea点击:

Rails 4: how to use named scope with has_many associations

ruby-on-railsrubyruby-on-rails-4

提问by emersonthis

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

在我的 Rails 4 应用程序项目(模型)has_many视频(模型)中。我在视频模型中有一个命名范围:

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 projectbut instead I get the number of videos in anyproject. It's as if .liveis not returning a subset from .videosbut rather replacing it.

我期望得到的是该特定项目中的项目数量,但我得到的是任何项目中的视频数量。就好像.live不是从中返回子集.videos而是替换它。

I see it explained herethat 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 .videosin this context] that doesn't seem to be happening.

我看到它解释这里是链接命名范围彼此应该有逻辑与但当应用于“协会法” [< -不知道对正确的术语组合.videos在此背景下]这似乎并没有发生。

What's the right way to do this?

这样做的正确方法是什么?

回答by Mike Waldrup

I believe it should read like this in Rails 4:

我相信它在 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.

rails 4 文档及其中的所有示例向您展示了将一个可调用对象传递到作用域以确保它每次都被调用。如果它不能像这样工作,请尝试将其实现为类方法,然后看看它对您的效果如何。

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

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

回答by mjnissim

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.

有关更多信息,请阅读此处