Rails has_many 与 finder_sql 和 name_scope 组合返回 nil

发布于 2024-12-08 19:33:13 字数 544 浏览 4 评论 0原文

例如,假设您有:

       class Model < AR::Base 
         has_many :somethings, :finder_sql => "SELECT * FROM somethings"
       end

       class Something < AR::Base
         named_scope :valuable {...code...}
       end

       # Assume you have one model but 0 somethings:  
       # Model.first.somethings          # => [] Good!
       # Model.first.somethings.valuable # => nil Bad! Should return [] !!!

仅当您在 has_many 关系中有 finder_sql 时才会发生这种情况。在其他情况下,它会按预期工作。

这是 Rails 2.3.14 的正常行为吗?

For example lets say you have:

       class Model < AR::Base 
         has_many :somethings, :finder_sql => "SELECT * FROM somethings"
       end

       class Something < AR::Base
         named_scope :valuable {...code...}
       end

       # Assume you have one model but 0 somethings:  
       # Model.first.somethings          # => [] Good!
       # Model.first.somethings.valuable # => nil Bad! Should return [] !!!

This only occurs when you have finder_sql in has_many relationship. In other cases it works as expected.

Is this normal behavior of Rails 2.3.14?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

感情洁癖 2024-12-15 19:33:13

是的,如果您指定finder_sql,那么您将无法附加范围。这是因为 finder_sql 适用于不符合正常 activeRecord 范例的情况。话虽如此,您的构建方式是不正确的。您不需要在这样的关系中存储没有过滤器的 select * 。关系的目的是将过滤器应用于另一个模型。因此, Model.find(params[:id]).somethings 的方式与调用 Something.all 完全相同。在后一种情况下,作用域将适用于您,因为 .all 可以限定作用域。

yes, if you specify finder_sql, then you will not be able to append scopes. that's because finder_sql is for situations that do not fit the normal activeRecord paradigm. That being said, the way you have this constructed is incorrect. you should not need to store a select * with no filters in a relationship like that. the purpose of a relationship is to apply a filter to the other model. so, the way you have it Model.find(params[:id]).somethings is exactly the same as calling Something.all . the scope will work for you in the latter case because .all can be scoped.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文